main2.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
26
27
28
29
30
31
32
33
34
35
36
// based on example2 (breaking circular references)

#include <iostream>
#include <memory>
#include <iostream>
using namespace std;

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>();

    cout  << "node1 count: " << node1.use_count() << endl; // 1
    cout  << "node2 count: " << node2.use_count() << endl; // 2

    // Without weak_ptr, both nodes do not destruct when exiting main, if the two following lines are active
    node1->next = node2;  // node1 points to node2 (node2 count incremented)
    node2->prev = node1;  // node2 weakly points back to node1 (node1 count not incremented)

    cout  << "node1 count: " << node1.use_count() << endl; // 1
    cout  << "node2 count: " << node2.use_count() << endl; // 2

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

    return 0;
}
Back to std_weak_ptr