skip to content

In C++, why does copying a std::unique_ptr fail to compile, and how do you hand its object to a new owner?

level: juniorimportance: must knowfreq 80%

answer

  1. one owner at a time
  2. copy operations are deleted
  3. std::move only casts
  4. source left holding nullptr
  5. returning a local needs no std::move

basics

~20 s

std::unique_ptr deletes its copy constructor and copy assignment, because two copies would both delete the same object. Ownership is moved instead: std::move hands it to the new owner, and the source is left holding nullptr.

solid answer

~40 s

A `std::unique_ptr` is the sole owner of its object, so the standard declares `unique_ptr(const unique_ptr&) = delete` and deletes the copy assignment as well: a copy would create two owners that each call `delete`. The type is move-only. To transfer ownership you write `std::move(p)`, which only casts `p` to an rvalue so that the move constructor or move assignment is chosen; afterwards the standard guarantees `p.get() == nullptr`, and the new owner is responsible for deleting the object. Returning a local `unique_ptr` by value needs no `std::move`, because a returned local is moved implicitly, which is why factories return `std::unique_ptr<T>`. A function that takes `std::unique_ptr<T>` by value is a sink: its caller must write `std::move` at the call, so every hand-off is visible in the code.

code

cpp · 30 lines
cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Node {
    std::string name;
    std::vector<std::unique_ptr<Node>> children;
    explicit Node(std::string n) : name(std::move(n)) {}
    void add(std::unique_ptr<Node> child) {          // sink: takes ownership
        children.push_back(std::move(child));
    }
};

std::unique_ptr<Node> make_button(std::string label) {  // factory
    auto node = std::make_unique<Node>(std::move(label));
    node->add(std::make_unique<Node>("icon"));
    return node;                                     // implicit move, no std::move
}

int main() {
    Node root("root");
    auto ok = make_button("OK");
    // auto copy = ok;                               // error: copy constructor is deleted
    root.add(std::move(ok));
    std::cout << std::boolalpha << (ok == nullptr) << ' '
              << root.children.size() << ' '
              << root.children[0]->children[0]->name << '\n';
}

go deeper

for a junior

Know that unique_ptr cannot be copied, that std::move is how ownership is handed over, and that the source becomes null afterwards.

for a middle

Explain why the copy operations are deleted, what std::move actually does, why a returned local needs no std::move, and how a vector of unique_ptr owns a tree.

for a senior

Spot hand-offs that leave a moved-from pointer in use, and read a deleted-copy error back to the line that needs std::move or a borrow instead.

for a principal

Treat move-only ownership as documentation: a by-value unique_ptr parameter or return type tells every reader who owns the object, which is worth more than any comment.

## What "unique" means `std::unique_ptr<T>` (header `<memory>`, since C++11) is a class template that **owns** one heap object: when the `unique_ptr` is destroyed, reset or assigned over, it calls its deleter on the pointer it holds, which for the default `std::default_delete<T>` means `delete p`. The standard describes this as **strict ownership**: at any moment exactly one `unique_ptr` is responsible for the object. Everything about how the type copies and moves follows from that one rule. ## Why the copy is deleted If `auto b = a;` were allowed, `a` and `b` would hold the same address and each would delete it when it goes out of scope — a **double delete**, which is undefined behaviour. So the standard's class synopsis declares: - `unique_ptr(const unique_ptr&) = delete;` - `unique_ptr& operator=(const unique_ptr&) = delete;` and specifies the type as *MoveConstructible* and *MoveAssignable* but not copyable. An implementation can reach the same result differently: libc++ declares only the move constructor, which makes the copy constructor *implicitly* deleted, so Apple clang reports the error in those words: ```plaintext error: call to implicitly-deleted copy constructor of 'std::unique_ptr<Node>' note: copy constructor is implicitly deleted because 'unique_ptr<Node>' has a user-declared move constructor ``` The same error appears anywhere a copy is required: passing a `unique_ptr` lvalue to a by-value parameter, `vec.push_back(p)`, capturing it by copy in a lambda, or copying a `std::vector<std::unique_ptr<T>>`. ## Transferring ownership with std::move `std::move(p)` does not move anything by itself; it is a cast that turns the expression `p` into an **rvalue** (an xvalue), so overload resolution picks the move constructor or move assignment. Those operations take the pointer and leave the source empty. Unlike most moved-from library objects, whose state is only "valid but unspecified", a moved-from `unique_ptr` has a precise postcondition: `u.get() == nullptr`. You may test it, reset it or assign a new pointer to it; dereferencing it is a null dereference. ```cpp auto panel = std::make_unique<Node>("panel"); root.add(std::move(panel)); // root now owns the node assert(panel == nullptr); // guaranteed by the standard ``` ## Returning from a factory A function that builds an object returns `std::unique_ptr<T>` **by value**. `return node;` on a local `unique_ptr` compiles without `std::move`: a returned local variable is treated as an rvalue first (and the copy may be elided entirely), so the move constructor is used. Writing `return std::move(node);` is unnecessary and can block elision. The caller receives sole ownership and can keep it, move it into a container, or convert it into a `std::shared_ptr` if the object later needs shared ownership. ## Containers of unique_ptr A scene graph whose nodes own their children is the textbook case: 1. Each `Node` holds `std::vector<std::unique_ptr<Node>> children`. 2. Adding a child moves the pointer into the vector with `push_back(std::move(child))` or `emplace_back`. 3. When a node is destroyed, its vector destroys every `unique_ptr`, which deletes every child, recursively. 4. The vector itself is move-only: copying the tree requires an explicit clone function. ## Why ownership by type beats ownership by comment With a raw owning pointer, `Node* make_button()` says nothing about who deletes the result, and every early `return` or thrown exception between the allocation and the hand-off is a potential leak. With `std::unique_ptr<Node> make_button()` the answer is in the type: if the caller ignores the result, the temporary deletes the node at the end of the full expression; if code between creation and `root.add(...)` throws, stack unwinding destroys the local `unique_ptr` and deletes the node. Ownership moves only where the source says `std::move` or where a function returns by value, so a reader can follow the object through the program by searching for those two things. ## One-way conversion to shared ownership A `std::unique_ptr<T>` rvalue converts to `std::shared_ptr<T>`: `std::shared_ptr<Node> s = std::move(u);` takes the object and leaves `u` empty. The reverse conversion does not exist, because a `shared_ptr` cannot prove it is the only owner. That asymmetry is why returning `unique_ptr` from a factory costs callers nothing: those who need shared ownership convert, everyone else keeps the cheaper single owner. ## Common mistakes - Expecting a copy to share the object, as `std::shared_ptr` would. - Believing `std::move` performs the move; it only enables one. - Using a `unique_ptr` after moving from it, as if it still pointed somewhere. - Writing `return std::move(local);` out of habit. - Assuming `unique_ptr` prevents aliasing: `get()` still hands out raw copies of the address, and the rules for those are a separate convention.

  • What state is a std::unique_ptr in after it has been moved from?
    Empty. The standard's postcondition for the move constructor and move assignment is that the source's `get()` returns `nullptr`. Most moved-from library objects are only 'valid but unspecified', but a moved-from `unique_ptr` is fully specified, so comparing it with `nullptr`, resetting it or assigning to it is safe. Dereferencing it is still a null dereference.
  • Can a std::vector<std::unique_ptr<Node>> be copied, and how do you duplicate such a tree?
    No. Copying the vector copies each element, and the element's copy constructor is deleted, so the copy fails to compile where it is used. The vector can be moved as a whole, and it relocates elements by moving them when it grows. To duplicate the tree you write a clone function that walks it and builds new nodes with `std::make_unique`.

  • Copying a unique_ptr shares the object, as shared_ptr does
  • std::move itself moves the pointer to the new owner
  • A moved-from unique_ptr still points at the old object
  • Returning a local unique_ptr requires return std::move(p)
  • unique_ptr stops any raw pointer from aliasing its object