Boost logo

Boost :

Subject: Re: [boost] [smart_ptr] enable_shared_from_this and shared_ptr to a base class
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2013-06-24 02:52:37


On Mon, Jun 24, 2013 at 10:28 AM, Adam Romanek <romanek.adam_at_[hidden]>wrote:

> Hi,
>
> I have a question related to using shared_from_this() and a shared_ptr
> to a base class.
>
> Here's a modified version of the enable_shared_from_this usage example
> from its documentation web page:
>
> #include <boost/enable_shared_from_**this.hpp>
> #include <boost/shared_ptr.hpp>
> #include <cassert>
>
> class X
> {
> public:
> virtual void foo() = 0;
> };
>
> class Y: public X, public boost::enable_shared_from_**this<Y>
> {
> virtual void foo()
> {
> shared_from_this();
> }
> };
>
> int main()
> {
> X* x_ptr = new Y;
> boost::shared_ptr<X> sp(x_ptr);
> sp->foo();
> }
>
> First, class Y is now derived from class X. Secondly, shared_ptr's
> template argument is now X and the parameter to the shared_ptr's
> constructor is now a pointer to X.
>
> Now, calling shared_from_this() in X and/or Y throws boost::bad_weak_ptr.
>
> Is this correct behavior? Is it documented somewhere?
>

This is expected, given the way it's implemented and described.
shared_from_this() description [1] mentions that there must be at least one
shared_ptr that owns the object. I didn't find any formal definition of the
"owns" relation but it doesn't look to me that it applies to your example,
because there is no shared_ptr pointing to Y in your code.

[1]
http://www.boost.org/doc/libs/release/libs/smart_ptr/enable_shared_from_this.html


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