When should you use unique_ptr, shared_ptr or weak_ptr?
Raw new and delete are error-prone, so C++11 introduced smart pointers in <memory> that express ownership.
std::unique_ptr<T>: exclusive ownership, cannot be copied, is movable, and has essentially zero overhead versus a raw pointer. Create withstd::make_unique.std::shared_ptr<T>: shared ownership through an atomic control block with a reference count; the object is destroyed when the last owner goes away. Create withstd::make_shared. Heavier, and the count is thread-safe but the object is not.std::weak_ptr<T>: a non-owning observer of a shared object, used to break cycles.lock()yields ashared_ptror null.
auto a = std::make_unique<Widget>();
auto b = std::make_shared<Widget>();
std::weak_ptr<Widget> w = b;
if (auto s = w.lock()) {
s->use();
}
Prefer unique_ptr by default, upgrade to shared_ptr only for genuine shared ownership, and never create two shared pointers from the same raw pointer, which causes a double free.