I’m trying to understand what’s going on in the following code. When object-a is deleted, does it’s shared_ptr member variable object-b remains in memory because object-c holds a shared_ptr to object-b?
class B
{
public:
B(int val)
{
_val = val;
}
int _val;
};
class A
{
public:
A()
{
_b = new B(121);
}
boost::shared_ptr<B> _b;
};
class C
{
public:
C()
{
}
void setRef( boost::shared_ptr<B> b)
{
_b = b;
}
boost::shared_ptr<B> _b;
};
int main()
{
C c;
{
A *a = new A();
cout << "a._b.use_count: " << a->_b.use_count() << endl;
c.setRef(a->_b);
cout << "a._b.use_count: " << a->_b.use_count() << endl;
delete a;
}
cout << c._b->_val << endl;
}
The
A-object will be cleaned up as soon asais deleted at the end of its block. But the shared_ptr it contains was subsequently copied, incrementing its reference count.Thus, the
B-object will have a reference count of 2 afterc.setRef(referenced by theA-object and by theC-object’sshared_ptr). Whenais deleted at the end of its block, then the reference count of theB-object drops to1again since onlyc‘s shared_ptr is referencing it now.After
cis destroyed at the end of main, itsshared_ptrwill be destroyed too as part ofc‘s destruction, and now as the reference count drops to zero, the pointed-toBobject will be deleted byshared_ptr.So, the reference counts of the
B-object: