Boost logo

Boost Users :

Subject: Re: [Boost-users] enable_shared_from_this()
From: Nathan Crookston (nathan.crookston_at_[hidden])
Date: 2013-02-04 12:23:52


Hi Dominique,

Dominique Devienne wrote:

> Can someone please explain why this code:
>
> struct Foo : boost::enable_shared_from_this<Foo> {};
> Foo* p_foo = new Foo;
> boost::shared_ptr<Foo> ptr_foo(p_foo->shared_from_this());
>
> is throwing?
>
> At the time you call shared_from_this, no shared_ptr has been created to
hold p_foo. The weak_ptr assumes the memory has been deallocated, since
there are no shared_ptrs pointing to it. Inheriting from
enable_shared_from_this is a guarantee that you will store the pointer in a
shared_ptr -- it's a precondition of calling shared_from_this.

Since Foo embeds a weak_ptr, why can't it new the pi_ on the spot?
> (I'm using Boost 1.44).
>
Hmm, it might be interesting to have shared_from_this create a shared_ptr
if none exists, but I don't know what that might complicate -- perhaps it
would cause issues at destruction?

> PS: On a related note, why doesn't boost::shared_ptr<Foo>(p_foo)
> (where p_foo is a raw Foo*) implicitly apply the aliasing Ctor, to
> share the same px, to avoid the classic bug of having several
> different pn on the same px, since p_foo derives from
> enable_shared_from_this()? Initially i thought that's what
> sp_enable_shared_from_this() and pe->_internal_accept_owner() were
> meant to do, but obviously that's not the case.
>
I suspect something like this could be made to work if the previous also
worked -- but the class is documented to *not* allow the previous to work.
I'd have to think about why (or maybe Peter will enlighten us).

HTH,
Nate



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