从基础 class 转换为派生 class 会抛出异常

Casting to derived class from base class throws exception

我有 3 个继承 类:Base -> Intermediate -> Derived.

为什么我用了dynamic_cast就抛出异常了?

class Base { ... };
class Intermediate : public Base { ... };
class Derived : public Intermediate { ... };

Base* base = new Derived();

// No throw
auto intermediate = static_cast<Intermediate *>(base);
auto derived1 = static_cast<Derived *>(base);
auto derived2 = static_cast<Derived *>(intermediate);

// All throw
// (vcruntime140d.dll): Access violation reading location [...].
auto intermediate = dynamic_cast<Intermediate *>(base);
auto derived1 = dynamic_cast<Derived *>(base);
auto derived2 = dynamic_cast<Derived *>(intermediate);

当转换为指向派生 class 的指针时,dynamic_cast 的操作数应该是指向 多态类型 的指针,即 class声明或继承了一个虚函数,而static_cast则没有这个约束。

在return中,如果操作数实际上没有指向目标类型对象的子对象,dynamic_cast会抛出异常,而static_cast则未定义。