Skip to content
Search

Std::unique ptr

lastmod 2018-08-17created 2015-09-136 edits

Containers

So far, so good. But it's hardly revolutionary. Writing a class that does what I've described so far is trivial, and you could do this even in the original C++ standard. In fact, the ill-fated (now deprecated) auto_ptr was exactly that, the first attempt at a RIAA pointer wrapper.

Unfortunately, the language had not evolved far enough for auto_ptr to work correctly. As a result, you cannot use it as something even slightly fundamental. For example, you cannot store auto_ptr objects in most containers. That is a very big problem.

C++11 solved these problems by adding rvalue references and move semantics. As a result, unique_ptr objects can be stored in containers, behave correctly when the container is resized or moved, and are destroyed along with the container when it is destroyed. Just as you would want.

Release

To give up ownership of the currently owned instance without freeing it, use the method called release. In this case, you must free the returned instance yourself.

Custom deleter

unique_ptr frees memory without being involved in allocating it, so if the memory was allocated some other way, such as with malloc instead of new, problems will occur. In that case, you need to implement a custom deleter.

Below is an example that allocates with malloc and frees through a custom deleter.

struct my_free
{
    void operator()(void* x) { free(x); }
};

int main()
{
    unique_ptr<int, my_free> a((int*)malloc(sizeof(int)));
    return 0;
}

Favorite site

References


  1. DevStory_of_LunaStar_-item_18-_std_unqiue_ptr.pdf ↩