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!