C++ boost::常量指针不起作用的动态\u指针\u强制转换?

C++ boost::常量指针不起作用的动态\u指针\u强制转换?,c++,gcc,boost,casting,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 ! } void foo(boost::shared_ptr a) { boost::shared_ptr b=boost::dynamic_poi

假设我有两个类,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 !
}
void foo(boost::shared_ptr a)
{
boost::shared_ptr b=boost::dynamic_pointer_cast(a);//错误!
}
使用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)
C:\Boost\include/Boost/smart_ptr/shared_ptr.hpp:在构造函数'Boost::shared_ptr<>::shared_ptr(const Boost::shared_ptr&,Boost::detail::dynamic_cast_tag)[带Y=const A,T=const B]:
C:\Boost\include/Boost/smart\U ptr/shared\U ptr.hpp:522:从“Boost::shared\U ptr Boost::dynamic\U pointer\U cast(const Boost::shared\U ptr&”)实例化[with T=const B,U=const A]'
src\a.cpp:10:从此处实例化
C:\Boost\include/Boost/smart\u ptr/shared\u ptr.hpp:259:错误:无法将'r->Boost::shared\u ptr::px'(类型为'const class A*const')动态转换为'const class B*'(源类型不是多态的)
可能出了什么问题

多谢各位

编辑 事实上,我发现了如何避免这种情况,但我不太明白


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

< P> <代码> DyrimoPoTythICAST 使用C++ <代码> DyrimaSkys< /Cord>内部和<代码> DyrimixCase< /Cult>要求您的类至少有一个虚拟方法。没有虚拟方法意味着没有vtable,如果没有vtable,则
dynamic\u cast
将无法确定哪些强制转换在运行时是可行的。

如果
Type
是一个具有至少一个虚拟成员函数(虚拟析构函数计数)的类,则只能在
Type*
指针上使用
dynamic\u cast
。由于
boost::dynamic\u pointer\u cast
在内部使用了
dynamic\u cast
,因此同样的限制也适用于它。

+1这是标准5.2.7/6中规定的:“否则,v应该是指向多态类型(10.3)的指针或左值。”@sbk因此它可以是析构函数,或任何其他方法。它只需要是虚拟的。是的,对于基类来说,虚拟析构函数是相当常见的。