example4_circular_reference.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::shared_ptr<Node> prev;

    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 points back to node1

    // This creates a circular reference, preventing both nodes from being destroyed

    return 0;
}
Back to std_shared_ptr