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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With