动态转换规范(规则)说明

Dynamic cast specification (rule) clarification

我们有dynamic_cast的一般形式:

dynamic_cast < new-type > ( expression )

我对这条规则 (5a) 的粗体部分特别困惑:

5: If expression is a pointer or reference to a polymorphic type Base, and new-type is a pointer or reference to the type Derived a run-time check is performed:

a) The most derived object pointed/identified by expression is examined. If, in that object, expression points/refers to a public base of Derived, and if only one object of Derived type is derived from the subobject pointed/identified by expression, then the result of the cast points/refers to that Derived object. (This is known as a "downcast".)

能否请您举例说明这部分不满足的地方?

以上摘录来自cppreference:cppreferenc

充实多重继承示例 @Peter 总结:

     Base1
     /   \  <-- Virtual inheritance here
  Base2  Base2
    |     | <-- Nonvirtual inheritance here and below
  Left   Right
    \     /
    Derived

Base1* p_base1 = new Derived();
Base2* p_base2 = dynamic_cast<Base2*>(p_base1); // Which Base2?

一个Derived对象中有两个不同的Base2对象,那么p_base2应该指向哪一个?

代码示例:

#include <iostream>

struct Base1 { virtual ~Base1() = default; };
struct Base2 : virtual Base1 { };
struct Left : Base2 { };
struct Right : Base2 { };
struct Derived : Left, Right {
    Derived() : Base1() {}
};

int main()
{
    Base1* p_base1 = new Derived();
    Base2* p_base2 = dynamic_cast<Base2*>(p_base1);
    std::cout << std::boolalpha;
    std::cout << "p_base1 == nullptr: " << (p_base1 == nullptr) << '\n';
    std::cout << "p_base2 == nullptr: " << (p_base2 == nullptr);
    delete p_base1;
}

这里要小心一点:Base1 实际上是继承的,所以只有一个 Base1 子对象,我们可以实际初始化 p_base1。但是,Derived 非虚拟地继承自 LeftRight,这意味着它有两个 Base2 实例。因此,向下转换失败。

输出:

p_base1 == nullptr: false
p_base2 == nullptr: true