I read about shared pointers and understood how to use. But I never understood the cyclic dependency problem with shared pointers and how weak pointers are going to fix thos
shard_ptr <----| shared_ptr <------
^ | ^ |
| | | |
| | | |
| | | |
| | | |
class A | class B |
| | | |
| ------------ |
| |
-------------------------------------
Now if we make the shared_ptr of the class B and A, the use_count of the both pointer is two.
When the shared_ptr goes out od scope the count still remains 1 and hence the A and B object does not gets deleted.
class B;
class A
{
shared_ptr sP1; // use weak_ptr instead to avoid CD
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void setShared(shared_ptr& p)
{
sP1 = p;
}
};
class B
{
shared_ptr sP1;
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
void setShared(shared_ptr& p)
{
sP1 = p;
}
};
int main()
{
shared_ptr aPtr(new A);
shared_ptr bPtr(new B);
aPtr->setShared(bPtr);
bPtr->setShared(aPtr);
return 0;
}
output:
A()
B()
As we can see from the output that A and B pointer are never deleted and hence memory leak.
To avoid such issue just use weak_ptr in class A instead of shared_ptr which makes more sense.