Unique Pointers
Explore how std::unique_ptr provides exclusive ownership of resources in C++, managing memory safely without copying. Understand its key methods, its specialization for arrays, and the std::make_unique helper introduced in C++14. This lesson helps you grasp unique pointers to enhance memory management effectively.
We'll cover the following...
std::unique_ptr exclusively takes care of its resource. It automatically releases the resource if it goes out of scope. If there is no copy semantic required, it can be used in containers and algorithms of the Standard Template Library. std::unique_ptr is as cheap and fast as a raw pointer, if you use no special deleter.
⚠️ Don’t use std::auto_ptr
Classical C++03 has a smart pointerstd::auto_ptr, which exclusively takes care of the lifetime of a resource. Butstd::auto_ptrhas a conceptional issue. If you implicitly or explicitly copy anstd::auto_ptr, the resource is moved. So instead of the copy semantic, you have a hidden move semantic, and therefore you often have undefined behavior. Sostd::auto_ptris deprecated in C++11 and you should use insteadstd::unique_ptr. You can neither implicitly or explicitly copy anstd::unique_ptr. You can only move it.
These are the methods of std::unique_ptr:
| Name | Description |
|---|---|
get |
Returns a pointer to the resource. |
get_deleter |
Returns the delete function. |
release |
Returns a pointer to the resource and releases it. |
reset |
Resets the resource. |
swap |
Swaps the resources. |
Methods of std::unique_ptr
In the following code sample you can see the application of these methods:
std::unique_ptr has a specialisation for arrays:
Special Deleters
std::unique_ptr can be parametrized with special deleters: std::unique_ptr<int, MyIntDeleter> up(new int(2011), myIntDeleter()). std::unique_ptr uses by default the deleter of the resource.
std::make_unique
The helper function std::make_unique was unlike its sibling std::make_shared forgotten in the C++11 standard. So std::make_unique was added with the C++14 standard. std::make_unique enables it to create a std::unique_ptr in a single step:
std::unique_ptr<int> up = std::make_unique<int>(2014).
In the next lesson, we will discuss shared pointers.