C++ Smart Pointers: Choosing the Right One

unique_ptr, shared_ptr, and weak_ptr each solve different ownership problems. Here's when to use each.

Key Insights

  • Default to unique_ptr for single ownership — it has zero overhead over raw pointers
  • shared_ptr has real costs: atomic reference counting and control block allocation
  • weak_ptr breaks circular references and enables safe observation without ownership

unique_ptr: The Default Choice

auto widget = std::make_unique<Widget>(args...);
// Transfer ownership
auto other = std::move(widget); // widget is now nullptr

shared_ptr: Shared Ownership

Only use when multiple owners genuinely need to control lifetime:

auto resource = std::make_shared<Resource>();
auto copy = resource; // reference count: 2

weak_ptr: Breaking Cycles

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev; // prevents circular reference
};

Liked this? There's more.

Every week: one practical technique, explained simply, with code you can use immediately.