`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_ptronly when ownership is truly shared. - Use
weak_ptrfor non-owning observation of shared objects. - Use
lock()on aweak_ptrbefore accessing the object. - Avoid ownership cycles.
- Prefer
unique_ptrwhen there is one clear owner.
Common Mistakes
- Using
shared_ptras the default smart pointer. Shared ownership should be a design decision. - Creating cycles with two
shared_ptrlinks. Cycles prevent reference counts from reaching zero. - Using a
weak_ptrwithout checking it. A weak pointer may refer to an object that is already gone. - Confusing sharing access with sharing ownership. Many objects can access something without owning it.
Quick Check
- Why is
parentaweak_ptrin the node example? - When should you prefer
unique_ptrovershared_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.