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?
lib_api*
a static member of the deleter class? – GramaryefreeInstance
in a custom derived class of the container class and that your container would containlib_object*
. In the derived class you have to implement the destructor that would callfreeInstance
on every element. – Autotomize