0

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;
}
newstudent
  • 65
  • 10
  • 3
    This is caused by parent. Your root node has an owning shared pointer to left and right and they both have an owning shared pointer to root causing a loop of ownership. You can solve this by making parent be a std::weak_ptr which is non owning. – drescherjm Aug 14 '20 at 13:00
  • 2
    You might want to check the value returned by `k.use_count()` immediately after the call to `foo()`. – G.M. Aug 14 '20 at 13:02
  • @drescherjm I have done it. But I just wanted to be sure that I understood it right. Thank you for the answer – newstudent Aug 14 '20 at 13:09
  • Here is the fixed code at ideone https://ideone.com/p0M4gN I will write an answer. – drescherjm Aug 14 '20 at 13:12
  • @drescherjm thank you, I have it in my other question, just wanted to be sure that destructors are not called because parent is shared_ptr too. :) – newstudent Aug 14 '20 at 14:05

0 Answers0