【问题标题】:Is a dynamic_cast<void*> guaranteed to work (i.e. be equal to static_cast<void*>) in the case of a non-polymorphic type?在非多态类型的情况下,是否保证 dynamic_cast<void*> 可以工作(即等于 static_cast<void*>)?
【发布时间】:2016-10-23 12:33:56
【问题描述】:

自从阅读this question 以来,我知道dynamic_cast&lt;void*&gt; 是检查对象指针的真实身份并确保任何基指针也将与最派生的指针(在强制转换之后)进行同等比较的最佳方法。

我不确定的是,这种强制转换在非多态情况下会给出明确且有用的结果。如果没有,我可以解决这个问题还是这是一个绝望的情况?

我要问的是这是否定义明确:

class A {};
class B : public A {};

int main()
{
  A a;
  B b;
  A* base_ptr = &b;

  void* pointer = dynamic_cast<void*>(&a); // is this value well-defined?

  if(dynamic_cast<void*>(&b) == dynamic_cast<void*>(base_ptr))
    std::cout << "Is this undefined or not?";
}

【问题讨论】:

    标签: c++11 polymorphism dynamic-cast


    【解决方案1】:

    此代码 doesn't compile 因此不会产生任何值,无论是明确定义的还是其他的。它违反了

    [expr.dynamic.cast]/6 否则,v 应为指向多态类型的指针或泛左值。

    【讨论】:

      猜你喜欢
      • 2014-05-29
      • 2012-02-13
      • 2015-05-04
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2021-02-03
      • 2019-09-23
      相关资源
      最近更新 更多