簡體   English   中英

C ++ shared_ptr從派生方法返回此結果

[英]C++ shared_ptr return this from derived method

我一直在使用這個:

struct Bar;

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

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

Foo * b = new Bar();
//...
b->GetBar();

我用它代替了緩慢的dynamic_cast 現在,我將代碼更改為使用std::shared_ptr

std::shared_ptr<Foo> b = std::shared_ptr<Bar>(new Bar());

如何更改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(); }
}

但是它不會編譯

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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM