Boost logo

Boost :

From: Frank Mori Hess (fmhess_at_[hidden])
Date: 2008-05-02 22:57:24


On Friday 02 May 2008 08:18, Peter Dimov wrote:
> What I had in mind is illustrated with the following:
>
> X * px = new X;
> // px->shared_from_this(); // throws bad_weak_ptr
> weak_ptr<X> wx = px->weak_from_this(); // OK
> assert( wx.use_count() == 0 ); // expired
> shared_ptr<X> sx( px );
> assert( wx.use_count() == 1 ); // shares ownership with sx

It's not clear to me that this kind of behavior could be implemented for
weak_ptr without changing its specification. Also, it doesn't allow for
distinguishing between "object alive but no shared_ptr owner yet"
and "shared_ptr expired or object destructed" cases. For the use case of
tracking signal/slot connections, the signal would want to be able to
distinguish between the two cases, temporarily blocking the connection in
the first, and disconnecting it permanently in the second.

What does seem to have the right semantics is for weak_from_this() to
return something like a shared_ptr<weak_ptr<T> >. Every call would return
a shared_ptr that points at the unique weak_ptr which will be assigned the
object's owning shared_ptr. The "object alive but no owning shared_ptr"
case would correspond to the weak_ptr being empty, and the "owning
shared_ptr expired case" would correspond to the weak_ptr being expired.
No changes to the specifications or implementations of shared_ptr/weak_ptr
would be required. This is really all my shared_from_that class is (I'm
starting to dislike my name choice btw).

-- 
Frank



Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk