Boost logo

Boost Users :

Subject: Re: [Boost-users] enable_shared_from_this()
From: Frank Mori Hess (fmh6jj_at_[hidden])
Date: 2013-02-07 09:18:59


On Thu, Feb 7, 2013 at 3:57 AM, John M. Dlugosz <mpbecey7gu_at_[hidden]> wrote:
>
> My old smart pointers (dating back to the '90's) had full support for
> initializing a smart pointer from a raw pointer even if it was already known
> to the smart pointer system. It was one of six _essential_ features (I
> called it “lost and found”) and I agree there were no troubles with it. It
> is easy to do when the class is derived from a helper base (like
> enable_shared_from_this does) and furthermore it doesn't need the CRTP.
>
> I agree that an extension to the now-standard enable_self_from_this could be
> implemented that gives a self_from_this that may be called during the
> constructor or as the first way to obtain a shared_ptr, also provide for
> "lost and found" usage, and not behave differently for any usage that is
> well-formed using the standard class (that is, it would be a pure
> extension).
>
> When changing some existing code to use shared_ptr, I've wished something
> like that was available, and missed my old class in this respect. For new
> code, in general use a Create static member that wraps the call to the
> (private) constructor so you can't create anything other than a shared_ptr,
> and the stuff that needs the shared ptr during "construction" gets moved to
> the stage 2, in the body of Create. In particular, if the object registers
> itself with collaborators (via shared pointers) you really wanted that part
> _in_ the constructor.

That sounds a lot like the the enable_shared_from_raw stuff in the trunk, see:

https://svn.boost.org/svn/boost/trunk/boost/smart_ptr/enable_shared_from_raw.hpp

there is a (non-CRTP) base class enable_shared_from_raw, plus a
shared_from_raw() free function. shared_from_raw can be used in
constructors, as long as some external shared_ptr eventually takes
proper ownership of the object after it is constructed. That means
throwing exceptions from the constructor after using shared_from_raw
(or in any derived constructor since ithe derived constructor would be
called later) causes bad things to happen.

It looks like I even wrote some tests for it, so the code probably
even still works.

--
Frank

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