在ctors中调用其他类的虚方法

Spo*_*ook 6 c++ polymorphism virtual inheritance

在关于在ctors和dtors中调用虚方法的问题中,引用了C++标准中的以下源代码:

struct V {
   virtual void f();
   virtual void g();
};
struct A : virtual V {
   virtual void f();
};
struct B : virtual V {
   virtual void g();
   B(V*, A*);
};
struct D : A, B {
   virtual void f();
   virtual void g();
   D() : B((A*)this, this) { }
};
B::B(V* v, A* a) {
    f(); // calls V::f, not A::f
    g(); // calls B::g, not D::g
    v->g(); // v is base of B, the call is well-defined, calls B::g

    // *** This line ***
    a->f(); // undefined behavior, a’s type not a base of B
    // *****************
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么a->f()在B的ctor中调用是一种未定义的行为?我们可以放心地假设,a在传递给B的ctor之前已经分配了,那么为什么不能正常工作呢?

V * v = new V();
A * a = new A();
B * b = new B(v, a);
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 2

a->f()当您创建 类型的对象时,该调用是未定义的D

在您自己的示例中,这a->f()是可以的,因为您A在创建实例之前已经创建了一个单独的实例B