A generic mechanism for giving RAII semantics to C-style APIs. More...
#include <RAII.hpp>
Public Member Functions | |
RAIIObject (const CTorArgs &... args) | |
Allocate a new object and take ownership of it. More... | |
RAIIObject (const APIType &obj, bool own=true) | |
Wrap an existing object. More... | |
const APIType | get () const |
Get the underlying C API object (eg. cudaStream_t ) More... | |
APIType | get () |
Get the underlying C API object (eg. cudaStream_t ) More... | |
APIType | operator* () |
const APIType | operator* () const |
operator APIType () const | |
Implicitly convert to the C API type, so you can just pass this object to the C library whence it came. More... | |
operator APIType () | |
Protected Types | |
using | APIType = typename AllocType::APIType |
The C API type. Something like cudaStream_t . More... | |
using | UnderlyingType = std::remove_pointer_t< APIType > |
A generic mechanism for giving RAII semantics to C-style APIs.
If you have a C API that works like this:
You can write an allocator class wrapping makeThingy()
and destroyThingy()
with this signature:
You can then instantiate RAIIObject<Thingy*, ThingyAllocator>
and have RAII semantics for Thingy
, thus eliminating many of the nightmares associated with using C APIs which have their own allocation functions .
This class defines operators allowing implicit conversion to the underlying C API type, allowing you to directly pass an RAIIObject<...>
to functions of the C library you've wrapped.
Thingy*
and give you that as the API object for you to play with. For instance, all NVIDIA® CUDA® APIs work like this: cudaStream_t
is secretly pointer to a magic internal struct, for example.AllocType | A wrapper type around the C allocate/deallocate functions. |
|
protected |
The C API type. Something like cudaStream_t
.
|
explicit |
Allocate a new object and take ownership of it.
|
explicit |
Wrap an existing object.
This is mostly useful for writing glue code that bridges between C and C++ APIs.
obj | The object to wrap. |
own | If true, ownership is taken of the object. This is almost always desirable. |
APIType sp::RAIIObject< AllocType, CTorArgs >::get | ( | ) |
Get the underlying C API object (eg. cudaStream_t
)
const APIType sp::RAIIObject< AllocType, CTorArgs >::get | ( | ) | const |
Get the underlying C API object (eg. cudaStream_t
)
sp::RAIIObject< AllocType, CTorArgs >::operator APIType | ( | ) | const |
Implicitly convert to the C API type, so you can just pass this object to the C library whence it came.