wiki:cpp-weak-ptr
Table of Contents
C++ weak_ptr
weak_ptr is a non-owning observer of an object managed by shared_ptr. It doesn't increment the reference count, so the object can be destroyed even if weak_ptrs exist. Use weak_ptr to break reference cycles and implement observer patterns without keeping objects alive.
Use weak_ptr to break cycles in shared_ptr graphs, particularly for parent-child or observer-subject relationships.
Example
This example demonstrates using weak_ptr to break a reference cycle between nodes.
// compile: g++ -o weak weak.cpp // run: ./weak // description: weak_ptr breaks reference cycles between objects #include <iostream> #include <memory> class Node { public: Node(int val) : value(val) { std::cout << "Node " << value << " created\n"; } ~Node() { std::cout << "Node " << value << " destroyed\n"; } int value; std::shared_ptr<Node> next; std::weak_ptr<Node> prev; // weak to prevent cycle }; int main() { { auto a = std::make_shared<Node>(1); auto b = std::make_shared<Node>(2); a->next = b; b->prev = a; // weak reference, doesn't keep a alive if (auto p = b->prev.lock()) { std::cout << "Prev node value: " << p->value << "\n"; } } // Both nodes destroyed here return 0; }
wiki/cpp-weak-ptr.md · Last modified: by 127.0.0.1
