C++ boost::shared_ptr 和动态转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4277810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:00:46  来源:igfitidea点击:

boost::shared_ptr and dynamic cast

c++boostdynamic-castboost-smart-ptr

提问by HolyLa

I have a problem using a shared_ptrof a base class, I can't seem to be able to call the derived class's methods when dereferencing it. I believe code will be more verbose than me:

我在使用shared_ptr基类的 a 时遇到问题,在取消引用它时似乎无法调用派生类的方法。我相信代码会比我更冗长:

class Base : public boost::enable_shared_from_this<Base>
{
  public:
    typedef  boost::shared_ptr<BabelNet> pointer;
};

class Derived : public Base
{
  public:
     static pointer  create()
                {
                        return pointer(new Derived);
                }
     void             anyMethod()
     {
        Base::pointer foo = Derived::create();
        // I can't call any method of Derived with foo
        // How can I manage to do this ?
        // is dynamic_cast a valid answer ?
        foo->derivedMethod(); // -> compilation fail
     }

};

回答by lijie

see static_cast with boost::shared_ptr?

看到带有 boost::shared_ptr 的 static_cast 吗?

you'll need to use dynamic_pointer_castto get the appropriate shared_ptrinstantiation. (corresponding to a dynamic_cast)

您需要使用dynamic_pointer_cast来获得适当的shared_ptr实例化。(对应于dynamic_cast

回答by icecrime

Shared pointer or not, when you have a pointer to a Base, you can only call member functions from Base.

无论是否共享指针,当您有指向 a 的指针时Base,您只能从Base.

If you really need to dynamic_cast, you can use dynamic_pointer_castfrom boost, but chances are that you shouldn't. Instead, think about your design : Derivedis a Base, and this is an extremely strong relationship, so think carefully about Baseinterface and if the concrete type really has to be known.

如果你真的需要dynamic_cast,你可以使用dynamic_pointer_castfrom boost,但很可能你不应该使用。相反,想想你的设计 : Derivedis aBase,这是一个非常强的关系,所以仔细考虑Base接口,以及是否真的必须知道具体的类型。

回答by C?t?lin Piti?

If derivedMethod is not declared in base class (virtual or not), then it is normal that the compilation would fail. The shared ptr knows and uses the base class (through the pointer it holds), and knows nothing about the derived class and its specific methods.

如果未在基类中声明派生方法(虚拟或非虚拟),则编译失败是正常的。共享 ptr 知道并使用基类(通过它持有的指针),并且对派生类及其特定方法一无所知。

回答by Simone

Your code wouldn't work even with raw pointers.

即使使用原始指针,您的代码也无法工作。

You need either to declare derivedMethod()method even in base class or to have a pointer to aDerivedobject.

derivedMethod()甚至需要在基类中声明方法或拥有指向Derived对象的指针。