I have read that weak_pointers can be used to break cyclic references.
Consider the following example of a cyclic reference
struct A
{
boost::shared_ptr<A> shrd_ptr;
};
boost::shared_ptr<A> ptr_A(boost::make_shared<A>());
boost::shared_ptr<A> ptr_b(boost::make_shared<A>());
ptr_A->shrd_ptr = ptr_b;
ptr_b->shrd_ptr = ptr_A;
Now above is a case of cyclic reference and I wanted to know how I can break
the cyclic reference above by using weak_ptr
?
Update : Based on suggestion received I came up with the following :
struct A
{
boost::weak_ptr<A> wk_ptr;
};
boost::shared_ptr<A> ptr_A (boost::make_shared<A>());
boost::shared_ptr<A> ptr_B (boost::make_shared<A>());
ptr_A->wk_ptr = ptr_B;
ptr_B->wk_ptr = ptr_A;
Will this be the correct approach ?
See Question&Answers more detail:os