q0987
q0987

Reputation: 35992

Example to use boost::weak_ptr to break cyclic dependencies

I have seen one of the usages of boost::weak_ptr is to break cyclic dependencies. Can someone give me a simple concrete example to illustrate this feature?

Thank you

Upvotes: 2

Views: 762

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63912

In simple terms:

{  // Enter scope

  shared_ptr<A> my_a(new A);
  shared_ptr<B> my_b(new B);

  my_a->remember_this_b( my_b );  // Stores a copy of a smart pointer
  my_b->remember_this_a( my_a );  // Stores a copy of a smart pointer

} // Leave scope.  my_a and my_b are destroyed.

If both these functions stored a shared_ptr, the objects would never be deleted, because neither shared_ptr would reach a reference count of zero.

However, if either one used a weak_ptr, the object pointed to by the weak_ptr would be destroyed when leaving the scope. And that would in turn destroy the last shared_ptr to the other object.

Upvotes: 5

Related Questions