c++ - 使用 dynamic_pointer_cast 时无法动态转换

标签 c++ c++11 shared-ptr dynamic-cast

为什么这段代码不起作用?

std::shared_ptr<Event> e = ep->pop();
std::shared_ptr<TrackerEvent> t;

t = std::dynamic_pointer_cast<TrackerEvent>(e);

我收到以下错误:

/usr/include/c++/4.6/bits/shared_ptr.h:386: error: cannot dynamic_cast '(& __r)->std::shared_ptr<Event>::<anonymous>.std::__shared_ptr<_Tp, _Lp>::get [with _Tp = Event, __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]()' (of type 'class Event*') to type 'class TrackerEvent*' (source type is not polymorphic)

TrackerEvent 继承自 Event 所以我想问题是我不能朝这个方向转换。但是 ep->pop() 可能返回类型为 EventTrackerEvent 的对象。我希望当我尝试将它转换为 TrackerEvent 并返回 NULL 时,我会知道我是否有 Event跟踪器事件...

我该怎么做?

最佳答案

编译器会在消息末尾告诉您发生了什么:

(source type is not polymorphic)

您的Event 基类需要至少有一个virtual 成员函数(即多态类型)以允许动态转换.您可以将 Event 的析构函数设为虚拟:

class Event
{
public:
    virtual ~Event() { /* whatever goes here, or nothing... */ }
    // ...
};

这是一个live example with polymorphic types ,显示代码编译(删除虚拟析构函数会导致编译错误 similar to the one you are seeing)。

正如 Luc Danton 所正确提及的那样在评论中,虚拟析构函数的默认版本可以这样定义(如果你的编译器在这方面是 C++11 兼容的):

class Event
{
public:
    virtual ~Event() = default;
    // ...
};

关于c++ - 使用 dynamic_pointer_cast 时无法动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374671/

相关文章:

c++ - 避免 gperf 输出文件中的 'warning: declaration UserSuppliedStruct does not declare anything'

c++ - 在 union 中使用字符数组

c++ - C++ 11 多线程中 lock_guard 的意外行为

c++ - shared_ptr 空指针和赋值

c++ - QFileDialog 打开第二个(可能是父级)不需要的窗口

c++ - 我如何模拟在 gmock 中存储为 unique_ptr 的对象?

c++ - 我可以在单一类型上定义可变参数模板函数吗?

c++ - g++ 错误 : specialization after instantiation (template class as friend)

c++ - 从shared_ptr推导出weak_ptr参数

c++ - 为什么存在 shared_ptr 的原子重载