|
Boost Users : |
From: Nat Goodspeed (nat_at_[hidden])
Date: 2008-05-30 14:57:40
Zhiyang Ong wrote:
> Should we usually, if not always, create and use weak pointers
> weak_ptrs with shared pointers shared_ptrs?
>
> Is setting all weak_ptrs to null the only reason for using weak_ptrs?
Ummm... let me try to paraphrase your question. I think you're asking:
When are weak_ptrs useful?
shared_ptr is based on reference counting, and the classic problem with
reference counts is circular chains. If instance A contains a shared_ptr
to instance B, and instance B contains a shared_ptr to instance A, both
are effectively immortal. Such cycles are often unintentional.
weak_ptr can be used to avoid that situation. If instance B holds a
weak_ptr to instance A, rather than a shared_ptr, then instance B's
weak_ptr no longer guarantees the survival of instance A. When the last
shared_ptr to instance A is destroyed, instance A will be deleted. If
instance A's shared_ptr is the only remaining shared_ptr to instance B,
instance B will be deleted as well.
Why use weak_ptr, though? Why not just store a simple A* in B?
The usefulness of weak_ptr arises when instance A's shared_ptr is NOT
the last remaining shared_ptr to instance B. In that case, instance A
will be deleted but instance B will survive. Some time later, a method
on instance B will try to traverse B's (now invalid) pointer to instance
A. If it's a simple A*, B's method has no way of knowing that instance A
is now dead, and you'll get a segfault. If it's a weak_ptr<A>, then B's
method can detect the absence of instance A and respond appropriately.
If that's not the question you're asking, then I'm sorry, I didn't
understand you.
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