C++ Smart Pointers
Smart Pointers
In the new and delete chapter, you learned that memory you get with new must be freed with delete. If you forget it, the memory is never given back. This is called a memory leak.
A smart pointer works like a normal pointer, but it frees the memory automatically when it is no longer used. To use smart pointers, include the <memory> library:
// Include the memory library
#include <memory>
The two most common smart pointers are unique_ptr and shared_ptr.
unique_ptr
A unique_ptr is the only owner of its memory. The memory is freed when the unique_ptr goes out of scope, for example when the function ends:
Example
unique_ptr<int> ptr(new int(25));
cout << *ptr;
You use * to get the value, just like with a normal pointer. But there is no delete. The memory is freed automatically when main() ends.
Note: Since C++14, you can also write make_unique<int>(25) instead of new int(25). It does the same, and you never have to write new at all.
Because a unique_ptr is the only owner, you cannot copy it:
Example
unique_ptr<int> ptr1(new int(25));
unique_ptr<int> ptr2 = ptr1; // Error: only one owner is allowed
shared_ptr
Unlike a unique_ptr, many shared_ptr variables can point to the same memory.
C++ keeps count of how many there are, and only frees the memory when the last one goes out of scope.
To create a shared_ptr, use the make_shared function.
In the example below, make_shared<int>(10) creates an int with the value 10, and gives you a shared_ptr that points to it:
Example
shared_ptr<int> ptr1 = make_shared<int>(10);
shared_ptr<int> ptr2 = ptr1;
cout << *ptr1 << "\n";
cout << *ptr2 << "\n";
cout << ptr1.use_count();
use_count() returns the number of owners. Both ptr1 and ptr2 point to the same value, so the count is 2.
Which One Should You Use?
- Use
unique_ptrby default. It is simple and fast. - Use
shared_ptrwhen several parts of your program need the same object.
In both cases, you do not need delete.