I am trying to learn how does the shared pointers work. Here is my example of cyclic dependence.
I want to know why aren't called my destructors at the end of the program? Is the problem because they are linked together and it can't exit that loop that makes of calling destructors?
Here is my code so please take a look at it.
Thanks in advance
#include <iostream>
#include <memory>
#include <string>
using namespace std;
struct Node {
string name;
shared_ptr<Node> left = nullptr;
shared_ptr<Node> right = nullptr;
shared_ptr<Node> parent=nullptr;
Node(string x) : name(x) { cout << "C" << name << endl; }
~Node() { cout << "D" << name << endl; }
string toString() {
string lStr{ "<none>" }, rStr{ "<none>" }, pStr{ "<none>" };
if (left != nullptr) lStr = left->toString();
if (right != nullptr) rStr = right->toString();
if (parent != nullptr) pStr = parent->name;
string res;
res += "{Me:" + name + " ";
res += "Parent:" + pStr + " ";
res += "Left:" + lStr + " ";
res += "Right:" + rStr + "}";
return res;
}
};
shared_ptr<Node> foo() {
shared_ptr<Node> root = make_shared<Node>("rootname");
root->left = make_shared<Node>("leftname");
root->right = make_shared<Node>("rightname");
root->left->parent = {root};
root->right->parent ={root};
return root;
}
int main()
{
shared_ptr<Node> k = foo();
cout << k->toString() << endl;
return 0;
}