Boost logo

Boost Users :

Subject: [Boost-users] [smart_ptr] enable_shared_from_this and shared_ptr to a base class
From: Adam Romanek (romanek.adam_at_[hidden])
Date: 2013-06-21 13:38:43


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?

I know that the example is a bit unrealistic since most of the time
shared_ptr is constructed directly from the pointer returned by 'new Y'
or created by make_shared() but still, this is something that bothers me.

WBR,
Adam Romanek


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