Fork me on GitHub

C++11 Smart Pointer wrappers for C libraries

A quick description of how I wrap SDL2 resources with C++11 smart pointers, so that cleaning up follows the RAII principle.

For example, with SDL, you load an image with IMG_Load(), and clean up with SDL_FreeSurface()

The desired interace using smart pointer RAII wrappers:

1. Wrapping with unique_ptr

The unique_ptr can be assigned a custom deleter class using operator(). This is shown below:

There is no memory wasted.

2. Wrapping with shared_ptr

Achieving the same with shared_ptr is slightly trickier. It isn't possible to specialize the shared_ptr type with a Deleter class like we did above for unique_ptr. Specifying a Deleter has been moved to the constructor.

In order to achieve the desired interface mentioned in the beginning, we need a way to have the Deleter be a part of the type definition. Here is my favourite way of doing this:

shared_ptr_with_deleter derives from std::shared_ptr and allows for an additional template parameter, our Deleter. If not provided, it defaults to the default deleter for the type T, which is same as what unique_ptr does.

The constructor simply calls the parent's, with the Deleter as a second argument. Similarly needs to be done with the reset function, so that it is overridden to enforce use of Deleter.

Since the class has no member data, we don't have to worry about slicing, and also don't need a virtual destructor, and no vtable. This means that no extra memory is used by our wrapper.

As before, we define new custom types for the shared_ptr versions: