68ejxfcj5669 68ejxfcj5669 - 1 year ago 103
C++ Question

unique_ptr deleter overhead

In normal C++ design, most objects can be deleted either by a

statement, the
function, or a library-specific equivalent to
. For such objects, the
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
by storing a
pointer as a data member in a custom
, but if multiple
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download