Search code examples
c++boostshared-ptr

Convert this pointer to boost::shared_ptr?


I am having a base class and i want to convert its this pointer to its derived class shared_ptr. I can`t use inheriting enable_shared_from_this in my case. So is there any other efficient way around?

eg

typedef boost::shared_ptr <a>  aPtr;
typedef boost::shared_ptr <b>  bPtr;

Class a{
    void fun();
}

class b : public a{
}

a::fun(){

     //how to carry out this conversion below
     bPtr bpointer = dynamic_cast<bPtr>(this);
}

Solution

  • You need boost::enable_shared_from_this. See the documentation:

    class Y: public boost::enable_shared_from_this<Y>
    {
    public:
    
        boost::shared_ptr<Y> f()
        {
            return shared_from_this();
        }
    }
    
    int main()
    {
        boost::shared_ptr<Y> p(new Y);
        boost::shared_ptr<Y> q = p->f();
        assert(p == q);
        assert(!(p < q || q < p)); // p and q must share ownership
    }