Possible alternative weak_ptr implementation
- I have recently been working on a magazine article about a smart weak
pointer implementation, without being aware of the work being done by Peter
Dimov for the boost weak_ptr. Now there's not much to be gained trying to
publish the article, so I guess I'll put my implementation up for discussion
The main difference in my weak_ptr is that it relies on support from the
referant class instead of from a related strong pointer (i.e. weak_ptr<T>
requires specific support from class T, instead of from shared_ptr<T>). How
it works is the referant (or target) object must allocate a boolean "true"
flag on the heap, and must clear it to "false" in its destructor. The flag
has a reference count that gets shared by any weak pointers that refer to
the target object. In this way, the flag can outlive the target object's
destruction. The weak pointers can simply check the value of the flag to see
whether their target object still exists or not.
So compared to the boost strong pointer/weak pointer combination, I see two
1. The target objects can be allocated and managed in any way (static,
automatic, heap, etc...) because its destructor always does the right thing.
2. It does not impact code which uses shared_ptr but not weak_ptr
As I understand it, the new boost:weak_ptr requires all boost::shared_ptr
objects to maintain two reference counts, even if the user code does not use
the weak pointer facilities. In fact, I had already found an implementation
along these lines from Dejan Jelovic's home page (http://www.jelovic.com/).
This approach seems a bit unfair, seeing as weak pointers are (IMHO) pretty
rarely used compared to strong pointers.
The disadvantage I see with my approach is that the target class has to have
explicit support, and (of course) can't be a built-in type. So that's not so
good in a generic library, but I think that weak pointers are something of
an usual case. The typical usage pattern for weak pointers (in data
structures which contain cycles) means that the objects in question are
usually not built-in types, and also not from third party code. If one of
these situations were actually to arise, then the target object would have
to be stored in some kind of wrapper I guess, but I can't think of a
situation where this would happen.
The easiest way to support weak_ptr in a target class is to add inheritance
from the simple weak_ptr_target base class which does all the necessary
stuff for you. I guess I shouldn't post the code directly to this list, but
if anyone is interested in seeing it (or can suggest where to post it) drop
me an email. Any comments welcomed.
Do You Yahoo!?
Get your free @... address at http://mail.yahoo.com