The C++11 standard introduced two new smart pointers, unique_ptr
and shared_ptr
. These new classes are very helpful for managing dynamically allocated memory.
The difference between these two smart pointers is that unique_ptr
implies exclusive ownership to a block of memory, whereas shared_ptr
allows for multiple ownership.
Both these smart pointers are defined in the memory
header file:
#include <memory>
unique_ptr
A unique pointer can be created using the std::make_unique()
function as follows:
std::unique_ptr<int> ptr = std::make_unique<int>(123);
Unique pointers are not assignable or copy-constructible, so they cannot be used in standard containers. However, they support move semantics so you can explicitly transfer ownership from one unique pointer to another using std::move()
. It is also possible to return a unique pointer from a function.
shared_ptr
A shared pointer can be created using the std::make_shared()
function:
std::shared_ptr<int> ptr = std::make_shared<int>(123);
Unlike unique pointers, shared pointers can be assigned and copied, so are suitable to use with standard containers.
Reference counting is used to ensure that memory is only deleted when there are no longer any references to it. Note that shared pointers can be used in multithreaded applications as updates to the reference counts are always atomic.
Also, it is possible to ‘move’ a unique pointer to a shared pointer (but not the other way round):
std::unique_ptr<int> p1 = std::make_unique<int>(55);
std::shared_ptr<int> p2 = std::move(p1);
This means that you could have a function that returns a returns a unique pointer and assign it directly to a shared pointer. This is particularly useful when implementing the factory pattern. If the creator function returns a unique_ptr
, then the calling function can decide whether to use a shared or exclusive ownership model.
Summary
C++11 introduces two new smart pointer types:unique_ptr
and shared_ptr
. These types can simplify memory usage and make code less prone to memory leaks. It is strongly recommended to use these in preference to the (now deprecated) auto_ptr
.