C++11 Smart Pointers are Not Just For Memory

AN IMPORTANT UPDATE TO THIS POST

I compiled all of this code using MS Visual Studio and it worked as I expected it to. However, when I tried using this approach with g++ and libstdc++ 3.3.6, the compilation failed. It turned out, the g++ implementation of unique_ptr compares the internal pointer to std::nullptr somewhere in its destructor.

At first I thought that maybe this is was a bug in libstdc++. However, I should have read the C++ standard more attentively: the pointer type managed by the smart pointers has to fulfill the nullable pointer requirement, which includes comparability to nullptr, so that is not a bug at all.

There is a work-around for that, which involves wrapping the handle into a type that satisfies the nullable pointer requirements.

I found this StackOverflow question asked by someone who ran into the exact same problem. The answer provides a good explanation as well as the workaround.

Moral: 1) library developers are smarter than you think they are, and certainly smarter than you; 2) RTFM



RAII is a useful idiom. It helps prevent resource leaks by making sure that resources are freed when they are no longer needed, and as such, provides a simple form of garbage collection.

The C++11 standard library provides a number of class templates (shared_ptr, unique_ptr, weak_ptr) to use this idiom for memory management.

However, memory is not the only resource that we have to manage. Sometimes we have to make sure a handle (e.g. a file descriptor, an OpenGL texture object, a HWND, etc.) returned by some library is freed properly.

There is a useful trick that allows you to use the standard smart pointer templates to manage such handles as well.

To accomplish this, we need to do two things:

  • Specify how the resource should be freed;
  • Make sure that internally, the smart pointer stores a handle, not a pointer

All smart pointer templates have an additional template parameter that allows us to specify a custom deleter type. A deleter type is basically just a class that has an overloaded operator() which accepts a pointer (or a handle, in our case), and frees the resource associated with it.

Let’s show this on a simple example. In this example, I’ll write a custom deleter for an OpenGL shader:

We can then use it with a smart pointer to replace the default deleter:

But we’re not done yet. This unique_ptr will store a pointer to GLuint internally, but we really want it to just store a GLuint, our handle. So how do we accomplish that?

The internal “dumb” pointer of std::unique_ptr<T, D> doesn’t just have the type “T*”. Its type is std::unique_ptr<T,D>::pointer, which is defined by the standard to be std::remove_reference<D>::type::pointer, or, if such type does not exist, T*.

In other words, if you add a typedef named “pointer” to your custom deleter, it will be used by the smart pointer internally. So, to get the desired behavior we just have to do this:

So, now our trick works! We create a new OpenGL shader during initialization and it will be deleted once the smart pointer goes out of scope!

There still is one caveat. The indirection operator won’t work as expected with this pointer. Writing something like:

glAttachShader(p, *smart_shader);

yields a somewhat cryptic compilation error in Visual Studio 2012. You should use the get() member function instead, like so:

glAttachShader(p, smart_shader.get());

It’s pretty easy to understand why this is happening by taking a look at the implementation of operator* in unique_ptr:

 

It’s trying to apply the indirection operator to a GLuint. Clearly, this should fail.

So why does it work when we don’t invoke the indirection operator on the smart pointer? That’s because the compiler won’t even attempt to generate code for a non-virtual member function of a class template if it’s never used (this behavior is, in fact, enforced by the language standard). Incidentally, code for virtual member functions will ALWAYS be generated (I’ll let you figure out why :) )

 

3 thoughts on “C++11 Smart Pointers are Not Just For Memory

  1. AlexMatto

    Impressive!

    Really cool trick for using RAII style with C-handles, and other things that lack RAII by default!

    Reply
  2. Pingback: C++11: Smart Pointers não tratam apenas de memória | Blog de Programação Literati

  3. Maximo

    I read a lot of interesting content here. Probably you spend a lot
    of time writing, i know how to save you a lot of time, there is an online tool that
    creates unique, SEO friendly posts in minutes, just type
    in google – laranitas free content source

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>