【问题标题】:boost::dynamic_pointer_cast with const pointer not working?带有 const 指针的 boost::dynamic_pointer_cast 不起作用?
【发布时间】:2011-02-08 17:51:36
【问题描述】:

假设我有两个类,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)

可能有什么问题?

谢谢。

编辑

其实我已经知道如何避免这种情况了,但我不确定。

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

【问题讨论】:

    标签: c++ gcc boost casting


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • +1 这是标准 5.2.7/6 中规定的:“否则,v 应是指向多态类型 (10.3) 的指针或左值。”
      • @sbk 所以它可能是析构函数,或者任何其他方法。它只需要是虚拟的。我做对了吗?
      • 是的,虚拟析构函数对于基类来说是相当普遍的。
      猜你喜欢
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多