Boost logo

Boost Users :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2006-12-01 13:23:28


Nat Goodspeed wrote:
>> Intrusive pointers are, IMO, the correct mechanism to hold a
>> tree together. They are efficient, effective, and easy to
>> understand. They work better than shared pointers for
>> recursive data structures. Unfortunately the lack of a
>> corresponding weak_ptr to go with boost::intrusive_ptr means I
>> either use a raw pointer to the parent, devise a strategy for
>> decrementing the pointers myself, or create my own weak
>> pointer.
>>
>
> If your data structure requires storing a pointer in a place which
> itself becomes invalid as soon as the referent becomes invalid (e.g.
> recursive deletion of a subtree), then I'm not convinced that weak_ptr
> is significantly better than a raw pointer.
>
> (Even "snipping loose" a subtree, but preserving it, doesn't seem to
> argue for weak_ptr as a parent pointer. In such a case, you'd want to
> clear the parent pointer anyway, wouldn't you?)
>
The use case here is this:

NodePtr base = make_tree();
NodePtr child = base.get("path/to/child");
base.reset();
Now, unless the parent knows that it owns the child and notifies it, the
parent pointer of child is dangling. A weak pointer can detect this
situation.

The reason I see for there being no weak_intrusive_ptr is that it is
quite simply impossible to implement while staying intrusive. Let's
remember what a weak pointer does: after the death of the object it
points to, it knows that it is now invalid. There being no notification
of pointers when other pointers get destructed, there's only one way to
do this: to keep the refcount for the object alive, so that the weak
pointer can check it.
But if the refcount is part of the object, as is the case for
intrusive_ptr, it's impossible to keep the refcount alive while
destroying the object.

In other words, the appeal of intrusive_ptr is that it doesn't require
any resources outside the object it points to. However, this restriction
makes it impossible to implement an efficient weak pointer.

Sebastian


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