dynamic_cast 作用于正在构造或析构的对象,而且该对象与当前构造或析构函数不属于同一个类或基类
C++-Undefined-Behavior-65
示例:
struct V {
virtual void foo();
};
struct A: virtual V {};
struct B: virtual V { B(V*, A*); };
struct C: A, B {
C(): B((A*)this, this) {}
};
B::B(V* v, A* a) {
dynamic_cast<B*>(v); // Well-defined, V is the base of B
dynamic_cast<B*>(a); // Undefined behavior, A is not a base of B
}
依据
ISO/IEC 14882:2003 12.7(5)-undefined
ISO/IEC 14882:2011 12.7(6)-undefined