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

Apo*_*hay 1 c++ 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);
}
Run Code Online (Sandbox Code Playgroud)

dal*_*lle 6

你需要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
}
Run Code Online (Sandbox Code Playgroud)