Skip to content


February 24, 2012

Part of the additions to the standard library are a couple of new smart pointers, std::shared_ptr and std::unique_ptr. In this post I will talk about std::unique_ptr. Firstly, it is defined in <memory>.

std::unique_ptr replaces the old std::auto_ptr. It is a smart pointer which can only hold one copy of a pointer, and deletes that pointer when its scope exits. std::unique_ptr can be used with normal or array variables, and a custom delete function can be specified. It cannot be copied, and assignment deletes the reference that it currently holds, if any.

For example, in the following code:

void foo()
  std::unique_ptr<int> p(new int);

  //do some stuff that might throw

if foo throws, or when the function exits, the memory held by p will automatically be deleted. You can also do this with an array type:

std::unique_ptr<int[]> p(new int[10]);

When p goes out of scope, the memory is deleted with delete[].

You can retrieve the pointer with std::unique_ptr::get, and std::unique_ptr::release gives up the pointer so that the object no longer manages it.

You can also specify your own deleter. For example, to use std::free, if the memory was allocated with std::malloc:

std::unique_ptr<int, void (*)(void*)> p(

where get_int_pointer is some appropriately defined function that returns an int*.

The deleter can be any type that can be used as a function, so if you had an object that managed your memory for you, as long as it has an operator(), you can use it for the deleter. Suppose that you had a class MemoryManager, you could do something like:

std::unique_ptr<Foo, MemoryManager> p(mem.createFoo(), mem);

From → Uncategorized

  1. Ivan Le Lann permalink

    Might be useful to explain unique_ptr other advantages against deprecated auto_ptr :

    It is not copyable but movable to prevent subtle bugs in our code, and allow usage in standard containers.
    And also the deleter let you hold a unique_ptr to an incomplete type.

    Thanks for your blog !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: