// 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;
}