Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cyclic destructors

Tags:

c++

in file a.h:

class B;
class A
{
public:
    B *b;
    A(B *b = nullptr)
    {
        this->b = b;
    }
    ~A()
    {
        delete this->b;
    }
};

in file b.h:

class A;
class B   
{
public:
    A *a;
    B(A *a = nullptr)
    {
        this->a = a;
    }
    ~B()
    {
        delete this->a;
    };
};

lets pretend that we have a pointer to an A *object, and we want to delete it:

// ...
A *a = new A();
B *b = new B();
A->b = b;
B->a = a;
// ...

delete a;

// ...

A's deconstructor will say delete B; i.e. call B's deconstructor. B's deconstructor will say delete A. death loop lé infinitè.

Is there a better way to write code to solve this problem? This isn't pressing question, just curious.

Thanks!

like image 628
iiian Avatar asked May 08 '26 10:05

iiian


1 Answers

Use smart pointers (i.e. std::shared_ptr) and weak pointers (i.e. std::weak_ptr) instead of pure pointers.

You have to define which class really owns which one. If none is owning the other, both should be weak pointers.

like image 100
Albert Avatar answered May 10 '26 03:05

Albert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!