In normal C++ design, most objects can be deleted either by a delete
statement, the free
function, or a library-specific equivalent to free
. For such objects, the unique_ptr
Deleter
implementation can be a stateless object that is eliminated through Empty Base Class Optimization. However, some libraries require using another object (which might contain a function pointer or some other context) to delete objects from that library.
typedef struct lib_object lib_object;
struct lib_api {
lib_object (*createInstance)();
void (*freeInstance)(lib_object *o);
};
One could wrap this in unique_ptr
by storing a lib_api
pointer as a data member in a custom Deleter
, but if multiple lib_object
instances needed to be managed, e.g. in a container, it would double the memory overhead of tracking the objects. What kind of pattern can be used to maintain RAII principles when dealing with this library, while still remaining memory efficient?
If there is only ever one lib_api
object, then you can have your deleter get a static pointer to it.
If there can be more than one lib_api
object then you have no choice but to store a pointer to it in the Deleter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With