example2_breaking_circular_references.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <memory>

class Node;

class Node {
public:
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev;  // Use weak_ptr to break the circular reference

    Node() { std::cout << "Node Constructor" << std::endl; }
    ~Node() { std::cout << "Node Destructor" << std::endl; }
};

int main() {
    std::shared_ptr<Node> node1 = std::make_shared<Node>();
    std::shared_ptr<Node> node2 = std::make_shared<Node>();

    node1->next = node2;  // node1 points to node2
    node2->prev = node1;  // node2 weakly points back to node1

    // Without weak_ptr, this circular reference would prevent both nodes from being destroyed

    return 0;
}
Back to std_weak_ptr