c – 什么时候vptr(指向vtable)被初始化为多态类?

前端之家收集整理的这篇文章主要介绍了c – 什么时候vptr(指向vtable)被初始化为多态类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这不是大约 “When VTABLE is created?”.而是应该初始化VPTR?它是在构造函数的开头/结尾还是在构造函数之前/之后?
A::A () : i(0),j(0)  -->> here ?
{
  -->> here ?
  //...
  -->> here ?
}

解决方法

用于虚拟调用的机器(通常是v表,但不需要)在ctor-initializer期间,在构建基础子对象之后和成员构建之前设置. Section [class.base.init]法令:

Member functions (including virtual member functions,10.3) can be called for an object under construction. Similarly,an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However,if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed,the result of the operation is undefined.

实际上,在构建基础子对象期间,存在虚函数机制,但是它是为基类设置的.第[class.cdtor]节说:

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@H_301_28@ in the constructor’s or destructor’s class and not one overriding it in a more-derived class. 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.

猜你在找的C&C++相关文章