加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:48:44 所属栏目:百科 来源:网络整理
导读:假设我有两个班,A和B,B是A班的小孩. 我也有以下功能: void foo(boost::shared_ptrconst A a){ boost::shared_ptrconst B b = boost::dynamic_pointer_castconst B(a); // Error !} 使用gcc编译给我以下错误: C:Boostinclude/boost/smart_ptr/shared_ptr.
假设我有两个班,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:Boostinclude/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:Boostinclude/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]'
srca.cpp:10:   instantiated from here
C:Boostinclude/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将无法确定哪些转换在运行时是可行的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读