Boost logo

Boost :

From: Ben Artin (macdev_at_[hidden])
Date: 2006-01-31 01:09:39


In article <008001c6260b$a0b7be90$0f00a8c0_at_david>,
 "David Maisonave" <boost_at_[hidden]> wrote:

> I can not find any example code that would justify the requirement for the
> weak_ptr other than the code in above link.

You need weak_ptr when you have cycles in your object graph. For example:

struct C1;
struct C2;

struct C1 {
   shared_ptr<C2> p;
}

struct C2 {
   shared_ptr<C1> p;
}

C1* p1 = new C1();
shared_ptr<C1> c1(p1);

C2* p2 = new C2();
shared_ptr<C2> c2(p2);

c1.p = c2;
c1.p = c1;

Given this code, neither the object at p1 nor the object at p2 will ever be
destroyed, because the cyclic dependency prevents refcounts from ever going to
zero. If you change either shared_ptr to a weak_ptr, the code correctly disposes
of both objects when both smart pointers go out of scope.

Ben

-- 
I changed my name: <http://periodic-kingdom.org/People/NameChange.php>

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk