开发者

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{
    vo开发者_StackOverflow社区id fun();
}

class b : public a{
}

a::fun(){

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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜