std::unique_ptr
- C++ course
- Intermediate
- Lesson 82/116
- 5 min
Learn exclusive ownership with std::unique_ptr.
std::unique_ptr
std::unique_ptr is a smart pointer that provides exclusive ownership of an object. When the owner goes out of scope the pointed object is automatically deleted. It is defined in <memory>.
Example: std::unique_ptr<int> p(new int(42)); creates an int object. You access the value with *p. When p goes out of scope the int is automatically deleted; no delete is needed. A unique_ptr cannot be copied but can be moved (with std::move). This guarantees there is exactly one owner.
Move semantics
A unique_ptr cannot be copied but can be moved. To transfer ownership to another unique_ptr you use std::move: auto p2 = std::move(p1);. After this p1 becomes empty (nullptr).
Moving means ownership is transferred; there is no copy. So there is always exactly one owner. Returning a unique_ptr from a function also moves: return p; transfers ownership to the caller. This is very useful in factory functions; the created object's ownership safely passes to the caller.
Practice Create a unique_ptr and print
Create a std::unique_ptr<int> with new int(42). Access the value with *p and print it with std::cout. Remember #include <memory> is required.
Starter code
#include <iostream>
#include <memory>
int main() {
// Create a unique_ptr<int> with value 42, print it
return 0;
}Sample solution
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> p(new int(42));
std::cout << *p;
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when a unique_ptr goes out of scope?
{
std::unique_ptr<int> p(new int(42));
} // end of scope- Nothing happens
- A memory leak occurs
- The program crashes
- The pointed object is automatically deleted Correct answer
Explanation: The unique_ptr destructor automatically deletes the object.
2 Declare a unique_ptr
std::____<int> p(new int(42));
std::unique_ptr<int> p(new int(42));
Explanation: unique_ptr provides exclusive ownership.
3 Match each feature to its meaning
| Term | Meaning |
|---|---|
std::unique_ptr |
Exclusive ownership |
std::move(p1) |
Transfer ownership |
*p |
Access value |
scope end |
Automatic deletion |