c – boost :: dynamic_pointer_cast,const指针不工作?

假设我有两个班,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 !
}

使用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)

什么可能是错的?

谢谢.

编辑

其实,我发现如何避免这种情况,但我不确定要理解.

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

解决方法

dynamic_pointer_cast在内部使用C dynamic_cast,dynamic_cast需要您的类至少有一个虚拟方法.没有虚拟方法意味着没有vtable,没有vtable dynamic_cast将无法确定哪些转换在运行时是可行的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...