Boost Users :
Subject: Re: [Boost-users] How & when to use weak_ptr
From: doug livesey (biot023_at_[hidden])
Date: 2011-07-02 13:37:48
Hmm -- so I guess, in the cases I'm talking about, I should store a
shared_ptr, and just return a const refererence.
Then, if I need to have a copy of the member elsewhere to manipulate, I
could return a weak_ptr.
Thanks for that!
On 2 July 2011 18:06, Richard Damon <Richard_at_[hidden]> wrote:
> 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 mailing list
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