Previously, we explored a basic implementation of unique_ptr
in "Understanding the Inner Workings of C++ Smart Pointers - The unique_ptr." Now, let's enhance that model by incorporating a custom deleter, similar to what the Standard Library provides.
Understanding the Inner Workings of C++ Smart Pointers - The Unique_ptr with Custom Deleter
by Andreas Fertig
From the article:
Let's first establish why somebody would want a custom deleter.
One example is that the object was allocated via a local heap, and such must be returned by calling the corresponding deallocation function.
Another example is
fopen
. This function returns aFILE*
object that you are supposed to delete by callingfclose
. A classic job for a unique pointer. But you cannot calldelete
on theFILE
pointer.Here are two examples of using a
void MyDeleter(Object* ptr)unique_ptr
with a custom deleter.
{
delete ptr;
}
unique_ptr<Object> alfred{new Object{}};
static_assert(sizeof(alfred) == sizeof(void*));
unique_ptr<Object, decltype(MyDeleter)> robin{new Object{}, &MyDeleter};
static_assert(sizeof(robin) == sizeof(void*) * 2);
Oh yes, the first object, alfred, doesn't provide a custom deleter. Only robin does. Behind the curtains, both do. Let's look at a modified unique_ptr implementation that handles the custom deleter case.
Add a Comment
Comments are closed.