Why can't we copy a std::unique_ptr, but we can move it?
Last updated
Because std::unique_ptr models exclusive ownership: only one pointer may own the resource at a time. Copying would create two owners of the same heap object, leading to a double-free; moving transfers ownership and leaves the source empty.
Copy is deleted by design:
The copy constructor and copy assignment of
unique_ptrare= delete, so the compiler rejects any copy attempt.If copying were allowed, both copies would call
deleteon the same pointer in their destructors: undefined behavior.
Move transfers ownership:
The move constructor copies the raw pointer out and sets the source's pointer to
nullptr, so exactly one owner remains.The moved-from
unique_ptris valid but empty (deleting nothing in its destructor).
You must opt into moving: Use
std::moveto pass ownership, since a named lvalue won't bind to the move constructor on its own.
[lang:cpp]
std::unique_ptr<int> a = std::make_unique<int>(42);
// std::unique_ptr<int> b = a; // error: copy deleted
std::unique_ptr<int> b = std::move(a); // ok: ownership moved, a is now null