Smart pointers: unique_ptr and shared_ptr

Difficulty: Intermediate

Question

What are smart pointers? Explain unique_ptr and shared_ptr, when to use each, and why make_unique and make_shared are preferred over new.

Answer

Smart pointers are RAII applied to dynamic memory, and using them well is the fastest way to remove 90 percent of manual memory bugs from C++ code. Let's look at what each one promises.

std::unique_ptr expresses exclusive ownership: exactly one unique_ptr owns an object at a time, and when it is destroyed, the object is deleted. It is not copyable (copy constructor is deleted) but is movable, so ownership can be transferred, for instance when returning from a function or pushing into a container with std::move. Think of it as the only key to a locker: you can hand the key over, but you cannot photocopy it. It has essentially zero overhead: with the default deleter it is the same size as a raw pointer and as fast. Use it as your default choice for owning a heap object, including polymorphic objects (unique_ptr<Base>, provided Base has a virtual destructor) and the pimpl idiom. There is an array form, unique_ptr<T[]>, that calls delete[].

std::shared_ptr expresses shared ownership: many shared_ptrs can point to the same object, and it is destroyed when the last owner goes away. Internally it keeps a control block with an atomic strong reference count, a weak count and the deleter, so a shared_ptr is typically two pointers wide, and copying it involves atomic increments. The atomic operations make reference counts thread-safe (though the pointed-to object itself is not), but they cost something. So do not default to shared_ptr; use it when ownership is truly shared, for example a cache entry used by several consumers whose lifetimes are not nested.

Why make_unique and make_shared? First, exception safety in older code: 'f(std::shared_ptr<T>(new T), g())' could leak if g threw between the new and the shared_ptr construction, depending on evaluation order. Second, make_shared performs a single allocation that holds both the object and control block, which is faster and more cache friendly than shared_ptr<T>(new T), which does two. Third, it avoids writing the type name twice and avoids naked new. There are caveats: make_shared cannot use a custom deleter, and the memory of the object is kept alive until the last weak_ptr disappears because it lives in the same block.

A couple of rules to mention. Pass a smart pointer by value or reference to a function only when that function participates in ownership; if it only uses the object, pass a raw pointer or reference (T* or T&) instead, taken with .get() or *. Never create two independent shared_ptrs from the same raw pointer, since each creates its own control block and the object is deleted twice. If you need a shared_ptr to 'this', inherit from std::enable_shared_from_this.

The deprecated std::auto_ptr, removed in C++17, had copy syntax that secretly moved; it was the reason unique_ptr and move semantics were created.

Code examples

unique_ptr transfers, shared_ptr shares

#include <iostream>
#include <memory>
#include <utility>

struct Res {
    Res()  { std::cout << "acquire\n"; }
    ~Res() { std::cout << "release\n"; }
};

std::unique_ptr<Res> make() { return std::make_unique<Res>(); }

int main() {
    auto u = make();
    // auto u2 = u;                    // error: not copyable
    auto u2 = std::move(u);            // ownership transferred
    std::cout << (u ? "u owns" : "u empty") << "\n";

    auto s1 = std::make_shared<int>(10);
    {
        auto s2 = s1;                  // shared ownership
        std::cout << s1.use_count() << "\n";
    }
    std::cout << s1.use_count() << "\n";
}

After the move, u is empty. The shared count goes to 2 while s2 lives, then back to 1. u2 releases the Res when main ends.

Key points

Common follow-up questions

Interview tips

Concepts covered

unique_ptr, shared_ptr, make_unique, ownership, reference counting

More C++ & STL questions