C++ — Transferring ownership with unique_ptr
Transfer exclusive ownership of an allocated object using std::unique_ptr and std::move.
A simple example
Read an owned value
- Start with An integer holding 2
- Do this Read through unique_ptr
- Result 2
#include <iostream>
#include <memory>
int main() {
auto value = std::make_unique<int>(2);
std::cout << *value << '\n';
}
2
Move a resource between owners
make_unique creates one owner of the vector. std::move permits the receiving unique_ptr to take ownership. The original pointer becomes empty. The receiver releases the vector automatically when it leaves scope.
A parcel desk can hand its single claim ticket to the next shift. In the program, moving the owning pointer transfers access to the stored value 7. The new owner can read it and the previous pointer is empty.
Run the example
C++17. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 lesson.cpp -o lesson
./lesson
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
int main() {
auto owner = std::make_unique<std::vector<int>>(2, 7);
auto receiver = std::move(owner);
std::cout << (owner == nullptr ? "transferred" : "owned") << '\n';
std::cout << receiver->at(0) << '\n';
return 0;
}
transferred 7
The original pointer becomes empty, and the receiver still has access to the first value, 7.
Try it yourself
Can you copy owner instead of moving it?
Check your answer
Copying a unique_ptr is rejected at compile time because two owners could otherwise release the same object.