将此指针转换为boost :: shared_ptr?

| 我有一个基类,我想将其指针转换为其派生类shared_ptr。在我的情况下,我不能使用继承enable_shared_from_this。那么还有其他有效的方法吗? 例如
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);
}
    
已邀请:
        您需要
boost::enable_shared_from_this
。请参阅文档:
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
}
    

要回复问题请先登录注册