So currently in our project there is a code that contains 2 classes which each contains a shared_ptr object of the other:
Class A
{
private:
std::shared_ptr<B> mB;
public:
void init()
{
mB = std::make_shared<B>();
mB->setA(this);
}
};
Class B
{
private:
std::shared_ptr<A> mA;
public:
void setA(shared_ptr<A> a)
{ mA = a; }
};
int main()
{
shared_ptr<A> objA = std::make_shared<A>();
}
And you can guess it, when the program quits and it calls the deletion of objA, it then call to delete B, and go on, and go on, and the application crashes.
What is the best way to solve that problem without a lot of code refactor? A code sample is appreciated since I suck at smart pointers.
Thanks a lot,
I tried to refactor the code a little by using weak_ptr for mB in class A but proly I did something wrong since the application crashes at launch.