On Friday 01 December 2006 16:15, Peter Dimov wrote:
Nat Goodspeed wrote:
It seems possible to implement weak_ptr notification by building a list of weak_ptr instances referencing a given object. If we don't want that list to consume additional heap memory, the list could itself be intrusive in the weak_ptr objects. If we want it to be efficient, we build a doubly-linked list. (This may call for a policy-based implementation so the consumer can decide which overhead is least noxious.)
This works. It's also completely independent of intrusive_ptr. You can implement such a weak pointer (and I know people who have done so) without ever using an intrusive_ptr or reference counting at all. The object destructor just goes over the list and zeroes the weak pointers. Threads are problematic and would probably require a per-object mutex.
Another option is to use
http://boost.org/libs/smart_ptr/sp_techniques.html#weak_without_shared
which also doesn't require intrusive_ptr and works for any object, and handles threads nicely. But you pay for a shared_ptr control block, so it probably won't satisfy intrusive_ptr users.
Both options are intrusive, but then, so is intrusive_ptr. :-)
My motivation for wanting the intrusive pointer is really design simplicity. For a tree I ran into problems trying share the pointer from within the pointee. enable_shared_from_this didn't work in all cases, and could get downright confusing, even when it did work. It also obviates one of the primary arguments from not using an intrusive pointer. If I use it, I already have to open up the pointee to modification. The reason I want the weak pointer is simply to prevent access to an invalid pointer. If I had an easy to use pair of intrusive/weak pointers, then I would just used them and not have to think about the details.