C++ shared_ptr从派生方法返回此信息

Mar*_*rry 1 c++ shared-ptr c++11

我一直在用这个:

struct Bar;

struct Foo 
{
   virtual Bar * GetBar() { return nullptr; }
}

struct Bar : public Foo
{
   virtual Bar * GetBar() { return this; }
}

Foo * b = new Bar();
//...
b->GetBar();
Run Code Online (Sandbox Code Playgroud)

我用这个而不是慢dynamic_cast.现在我已经改变了我要使用的代码std::shared_ptr

std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar());
Run Code Online (Sandbox Code Playgroud)

如何更改GetBar返回的方法std::shared_ptr并获得与原始指针相同的功能(不需要dynamic_cast)?

我试过这个:

 struct Foo : public std::enable_shared_from_this<Foo>
 {
     virtual std::shared_ptr<Bar> GetBar() { return nullptr; }
 } 


struct Bar : public Foo
{
    virtual std::shared_ptr<Bar> GetBar() { return shared_from_this(); }
}
Run Code Online (Sandbox Code Playgroud)

但它不会编译

ken*_*ytm 5

std::enable_shared_from_this<Foo>::shared_from_this()返回一个shared_ptr<Foo>.所以你需要一个明确的指针向下转换.

virtual std::shared_ptr<Bar> GetBar() {
    return std::static_pointer_cast<Bar>(shared_from_this());
}
Run Code Online (Sandbox Code Playgroud)