I have two classes, A and B, that have a shared_ptr pointing to each other (A has a shared_ptr to B, B has a shared_ptr to A).
I'm trying to have the destructor of both classes called when getting out of the scope, but it doesn't work. No destructor is called.
Here's an example code:
class B;
class A
{
public:
A() { std::cout << "Constructor A" << std::endl; }
~A() { std::cout << "Destructor A" << std::endl; }
std::shared_ptr<B> b;
};
class B
{
public:
B() { std::cout << "Constructor B" << std::endl; }
~B() { std::cout << "Destructor B" << std::endl; }
std::shared_ptr<A> a;
};
int main()
{
std::shared_ptr<A> a = std::make_shared<A>();
a->b = std::make_shared<B>();
a->b->a = a;
}
How could I fix this?