使用const指针不能工作的boost :: dynamic_pointer_cast?

ere*_*eOn 10 c++ gcc boost casting

假设我有两个类,A和B,其中B是A的子类.

我还有以下功能:

void foo(boost::shared_ptr<const A> a)
{
    boost::shared_ptr<const B> b = boost::dynamic_pointer_cast<const B>(a); // Error !
}
Run Code Online (Sandbox Code Playgroud)

使用gcc编译给出了以下错误:

C:\Boost\include/boost/smart_ptr/shared_ptr.hpp: In constructor 'boost::shared_ptr< <template-parameter-1-1> >::shared_ptr(const boost::shared_ptr<Y>&, boost::detail::dynamic_cast_tag) [with Y = const A, T = const B]':
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:522:   instantiated from 'boost::shared_ptr<X> boost::dynamic_pointer_cast(const boost::shared_ptr<U>&) [with T = const B, U = const A]'
src\a.cpp:10:   instantiated from here
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:259: error: cannot dynamic_cast 'r->boost::shared_ptr<const A>::px' (of type 'const class A* const') to type 'const class B*' (source type is not polymorphic)
Run Code Online (Sandbox Code Playgroud)

什么可能是错的?

谢谢.

编辑

实际上,我发现了如何避免这种情况,但我不确定.

我的A类是空的(因此没有虚拟析构函数).如果我添加一个虚拟析构函数,则错误消失.但我不明白,为什么这需要?

sbk*_*sbk 18

dynamic_pointer_castdynamic_cast内部使用C++ 并dynamic_cast要求您的类至少拥有一个虚拟方法.没有虚拟方法意味着没有vtable,没有vtable dynamic_cast将无法确定哪些强制转换在运行时可行.

  • +1这在标准中的5.2.7/6中是强制性的:"否则,v应该是多态类型的指针或左值(10.3)." (2认同)