Lesson contents

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

  1. Start with An integer holding 2
  2. Do this Read through unique_ptr
  3. Result 2
The smart pointer owns the integer. The star reads its value and the pointer releases it at the end of the block.
lesson.cpp
#include <iostream>
#include <memory>

int main() {
    auto value = std::make_unique<int>(2);
    std::cout << *value << '\n';
}
Output
2
Advertisements

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.

Before handover: First owner holds 7. Action: Transfer ownership. After handover: New owner reads 7.
Hand over the only claim ticket

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
lesson.cpp
#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;
}
Output
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.

C++ language and library reference

Related tags

  • C++
  • ownership
  • RAII
  • move semantics