首页 > 代码库 > [C++]在构造函数及析构函数中调用虚函数
[C++]在构造函数及析构函数中调用虚函数
(ISO/IEC 14882:2011 section 12.7.4):
Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2).
When a virtual function is called directly or indirectly from a constructor or from a destructor, including
during the construction or destruction of the class’s non-static data members, and the object to which the
call applies is the object (call it x) under construction or destruction, the function called is the final overrider
in the constructor’s or destructor’s class and not one overriding it in a more-derived class.
(ISO/IEC 14882:2011 section 12.7.4):
If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete
object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the
behavior is undefined.
在ctor及dtor中出现虚函数的调用,调用的虚函数实现为当前ctor/dtor处在的class那一级的实现。
也即是说class X的ctor/dtor中出现了继承的虚函数vfun()的调用,不管X是否被其他类继承,vfun是否被X的子类重写,vfun的实现都为X一级的版本(X重写的版本或者从X父类继承来的版本)。
如果在X的ctor/dtor中调用vfun()的对象非X及其父类,则会导致undefined behavior。
//Example from ISO/IEC 14882:2011 section 12.7.4struct 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 a->f(); // undefined behavior, a’s type not a base of B}
如果在ctor/dtor内调用纯虚函数会怎么样呢?
(ISO/IEC 14882:2011 section 10.4.6):
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a
virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed)
from such a constructor (or destructor) is undefined.
在ctor/dtor内调用纯虚函数会导致undefined behavior。
[C++]在构造函数及析构函数中调用虚函数