All Courses
OOP: RAII AND OWNERSHIP

`shared_ptr` and `weak_ptr`

Concept Definition

std::shared_ptr represents shared ownership. The object stays alive while at least one shared_ptr owns it. std::weak_ptr observes the same object without increasing the ownership count.

Think of a shared online document. Several people can keep it alive by working on it, but a bookmark should not count as an active owner.

Why It Matters

Some objects genuinely need shared lifetime: cached data, graph nodes, or resources used by multiple systems. shared_ptr handles that lifetime with reference counting. However, shared ownership should be intentional, not a default habit.

weak_ptr matters because two shared_ptr objects can form a cycle. In a cycle, each object keeps the other alive forever. A weak pointer breaks that ownership loop.

Syntax Block

auto owner = std::make_shared<Type>(); // shared owner
std::weak_ptr<Type> observer = owner;  // non-owning observer

Explained Code

Example: Tree Node With Weak Parent

#include <memory> // std::shared_ptr, std::weak_ptr
#include <string> // std::string
#include <vector> // std::vector

class Node {
private:
    std::string name;                         // node label

public:
    std::vector<std::shared_ptr<Node>> children; // children are owned by parent side
    std::weak_ptr<Node> parent;               // parent link does not own

    explicit Node(std::string nodeName) : name(std::move(nodeName)) {} // initialize
    const std::string& getName() const { return name; } // read label
};

Children are shared owners because they may be referenced elsewhere. The parent link is weak because it should not keep the parent alive forever.

Key Points / Rules

  • Use shared_ptr only when ownership is truly shared.
  • Use weak_ptr for non-owning observation of shared objects.
  • Use lock() on a weak_ptr before accessing the object.
  • Avoid ownership cycles.
  • Prefer unique_ptr when there is one clear owner.

Common Mistakes

  1. Using shared_ptr as the default smart pointer. Shared ownership should be a design decision.
  2. Creating cycles with two shared_ptr links. Cycles prevent reference counts from reaching zero.
  3. Using a weak_ptr without checking it. A weak pointer may refer to an object that is already gone.
  4. Confusing sharing access with sharing ownership. Many objects can access something without owning it.

Quick Check

  1. Why is parent a weak_ptr in the node example?
  2. When should you prefer unique_ptr over shared_ptr?

Viva Answer

shared_ptr gives shared ownership through reference counting. weak_ptr observes a shared object without owning it and helps prevent ownership cycles.