Boost logo

Boost :

Subject: Re: [boost] Thoughts on make_shared and shared_from_this in aconstructor
From: Peter Dimov (pdimov_at_[hidden])
Date: 2009-03-07 17:17:41


Frank Mori Hess:
> On Saturday 07 March 2009, Peter Dimov wrote:
> > I can't think of a good way to pass this shared_ptr to the
> > enable_shared_from_this base since we have no control over T.
>
> But we do have control over T. That is, if the user wants to define a
> class T which uses shared_from_this in its constructor, we can require
> them to fulfill certain requirements, right? Maybe something like
> providing a special constructor signature which accepts the owning
> shared_ptr, plus maybe an extra tag object to insure it doesn't get
> confused with other constructor overloads. Although if the T constructor
> is receiving the shared_ptr directly, it wouldn't have any need to call
> shared_from_this().

This is one possible solution. Define a "token class" weak_this into which
make_shared can stuff the owning shared_ptr, so that when

    make_shared<X>( weak_this(), 1, 2 )

is called, X::X receives a non-empty weak_this.

This works but requires cooperation from X. In principle, X may be derived
from Y which in turn is derived from enable_shared_from_this<Y>. Y knows
about weak_this but X may not.

Another possible solution is to stick the "weak this" into a thread-local
static member of enable_shared_from_this<Y>. This also works but (absent
compiler support for thread locals) doesn't fit into the header-only nature
of shared_ptr.


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