6
在問題其他類的虛擬方法中爲約calling virtual methods in ctors and 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
// *****************
}
我的問題是:爲什麼在B的構造函數調用a->f()
是一個未定義的行爲?我們可以放心地假設,a
在傳遞給B的ctor之前已經被分配了,爲什麼不能正確地工作呢?當你創建D
類型的對象
V * v = new V();
A * a = new A();
B * b = new B(v, a);