Skip to content

Lesson 2 of 9 · 26m

Smart Pointers as an Ownership Vocabulary

Use unique_ptr, shared_ptr, weak_ptr, and raw references to communicate ownership precisely instead of treating smart pointers as memory decoration.

The first rule I give new hires is simple: std::shared_ptr is not the default. Shared ownership is a design decision with runtime cost, coupling cost, and usually a cycle cost. Most objects need exactly one owner. Everything else should merely observe. When the pointer type matches that truth, the codebase explains itself.

Default to unique ownership

std::unique_ptr means "this object owns what it points at, and ownership can move but not copy."

auto parser = std::make_unique<JsonParser>(config);
auto result = parser->parse(payload);
process(std::move(parser));       // ownership transfers explicitly

Use std::make_unique unless a custom deleter or constructor visibility issue prevents it. It avoids repetition, is exception-safe in multi-argument calls, and makes intent obvious.

A function signature should answer the ownership question:

void inspect(const Parser& parser);          // borrow; no ownership
void consume(std::unique_ptr<Parser> parser); // takes ownership
Parser& mutable_access(Parser& parser);       // non-null borrow, caller owns

Do not pass std::unique_ptr& merely to observe the pointee. That exposes the ownership mechanism for no benefit and prevents callers from using stack objects.

Shared ownership is a graph problem

std::shared_ptr is appropriate when lifetimes genuinely overlap and no single scope can own the object: asynchronous completion state, shared immutable configuration, or objects referenced by independent subsystems.

struct Session : std::enable_shared_from_this<Session> {
    void start() {
        auto self = shared_from_this();
        socket_.async_read(buffer_, [self](auto ec, auto n) {
            if (!ec) self->handle_read(n);
        });
    }
};

The pattern keeps the session alive while asynchronous work exists. It also creates the classic trap: callbacks capturing shared_ptr graphs can form cycles. A connection owns a handler, the handler owns the connection, and nothing ever dies.

Use std::weak_ptr when an observer must not extend lifetime:

std::weak_ptr<Session> weak = session;
if (auto live = weak.lock()) {
    live->write(response);
}

weak_ptr is not a performance optimization. It is a statement that the observer has no right to keep the object alive.

Raw pointers are not automatically evil

In modern C++, a raw pointer or reference often means non-owning access. That is useful when the object's lifetime is externally guaranteed. The mistake is not using raw pointers; the mistake is failing to document who owns the object and how long it lives.

void render(Document& doc);       // document must outlive call
void render(Document* doc);       // nullable observer

Failure modes senior engineers watch for

shared_ptr copied unnecessarily into hot paths costs atomic reference-count traffic. enable_shared_from_this requires that the object already be owned by a shared_ptr; calling shared_from_this in a constructor is undefined behavior territory in practice. Arrays need std::unique_ptr<T[]> or preferably std::vector, not a scalar deleter.

Field notes

  • If every object is in shared_ptr, the design has no ownership model; it has garbage collection with worse ergonomics.
  • make_shared usually allocates object and control block together, which is efficient but keeps memory alive while weak references remain.
  • Do not create two independent shared_ptr objects from the same raw pointer; they will double-delete.
  • A custom deleter belongs in ownership design: std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> beats manual cleanup.

Was this lesson helpful?

Sign in to rate