Horizon Posted September 9 Share Posted September 9 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 a FILE* object that you are supposed to delete by calling fclose. A classic job for a unique pointer. But you cannot call delete on the FILE pointer. Here are two examples of using a unique_ptr with a custom deleter. void MyDeleter(Object* ptr) { 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.View the full article Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.