std::unique_ptr: Default Ownership
intermediate25 min readLesson 108 of 204
make_unique, move-only transfer, and the signature discipline of not naming smart pointers in observers.
std::unique_ptr<T> is the default smart pointer: exclusive ownership,
zero overhead over a raw pointer, deleted when the unique_ptr dies.
#include <memory>
auto p = std::make_unique<Widget>(arg1, arg2); // prefer make_unique
p->draw();
auto q = std::move(p); // ownership transfers; p is now nullptr
// p->draw(); // UB: p is empty โ check it first
The rules:
- Always
make_unique, notnew: one allocation, exception safety, no nakednewin application code. - Non-copyable, movable. Copying would create two owners โ the exact bug the type exists to prevent.
- Arrays:
std::unique_ptr<T[]>exists butstd::vector<T>is almost always the right answer. - Pass
unique_ptrwhen you transfer ownership; passT&orT*when you merely use the object. Functions that observe should not name smart pointers in their signatures.