1
返回此我已使用該:C++ shared_ptr的衍生自方法
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(); }
}
,但它不會編譯
當然'GetBar'不應該返回'酒吧*' - 但'美孚*' –
@EdHeal這會破壞目的。 –