A class supporting the implementation of handles with a 32-bit integer value.
More...
#include "nn/nlib/HandleMaker.h"
template<class HBODY>
class nn::nlib::HandleMaker< HBODY >
A class supporting the implementation of handles with a 32-bit integer value.
- Template Parameters
-
HBODY | Handle instance type. |
- Description
- A class providing a mechanism to associate a 32-bit integer value (a handle) with an object (a handle instance). Using
HandleMaker
enables you to easily provide handles with the following features:
- Access to the handle instance through the handle is thread safe.
- Even if you use the handle after closing it (i.e. the handle is no longer valid), an error (generally,
EBADF
) can be returned without causing a crash.
- The above features apply also for cases where the handle is closed from a different thread.
- Since an integer value that acts as a handle will not be reused immediately, you can avoid unintentional access to the handle instance.
- -1, 0, 1, 2, or 3 will not be assigned as a handle value.
- Below is sample code to define a simple handle.
class MyHandleBody {
public:
static const size_t N = 128;
public:
MyHandleBody() {
valid_ = false;
}
~MyHandleBody() noexcept {
assert(!valid_);
}
assert(!valid_);
{
}
valid_ = true;
return 0;
}
if (!valid_) {
return EBADF;
}
{
}
valid_ = false;
return 0;
}
if (!valid_) {
return EBADF;
}
{
}
return 0;
}
Private:
bool valid_;
};
errno_t myhandle_open(
int* handle) {
MyHandleBody* p = new(std::nothrow) MyHandleBody();
if (!p) return ENOMEM;
e = p->Initialize()
delete p;
return e;
}
e = maker.AttachHandleBody(handle, p);
(void)p->Finalize();
delete p;
return e;
}
return 0;
}
errno_t myhandle_access(
int handle, ......) {
e = maker.GetHandleAccess(handle, &access);
e = access->access_method(......);
return e;
}
errno_t myhandle_close(
int handle) {
e = maker.GetHandleAccess(handle, &access);
e = access->Finalize();
return e;
}
Definition at line 87 of file HandleMaker.h.
◆ AttachHandleBody()
Gets a handle that should be associated with the handle instance.
- Parameters
-
[out] | handle | Pointer to the handle associated with body. |
[in] | body | Handle instance to be associated with the handle. |
- Return values
-
0 | Success. |
ENFILE | No handle is available that can be assigned. |
Definition at line 192 of file HandleMaker.h.
◆ GetHandleAccess()
Obtains access from a handle to the handle instance.
- Parameters
-
[in] | handle | Handle obtained with AttachHandleBody() . |
[out] | access | Accessor to an instance corresponding to the handle. |
- Return values
-
0 | Success. |
EBADF | The handle is not valid. |
Definition at line 259 of file HandleMaker.h.
The documentation for this class was generated from the following files: