Boost logo

Boost Users :

Subject: Re: [Boost-users] How & when to use weak_ptr
From: Richard Damon (Richard_at_[hidden])
Date: 2011-07-02 13:06:59


On 7/2/11 12:28 PM, doug livesey wrote:
> Hi -- I'm loving how easy shared_ptr makes object handling, but am not
> sure about how to use weak_ptr.
> Should I use it in places where previously I would have, say, returned
> a const reference?
>
A weak pointer should be used where you need to keep a pointer around
for an object, but you do not insist that the object stays around, but
you do want to know if the object has gone away.

The main use of this is circular references, where for example, object A
has a pointer to B, and object B has a pointer to A. If both of these
were regular shared_ptrs than once this combination was created, then it
would never go away as both A and B have a strong reference to them.
Making one of the links a weak pointer, says that when all other
shared_ptr references to the pair go away, then both A and B go away.

You do have to be a bit careful and think about the consequences, and if
you change the pointer from B to A to be a weak-ptr, then if all
shared_ptr references to A go away, but you still have some to B, then A
will go away but not B, so B needs to be able to handle that case.

-- 
Richard Damon

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net