gpt4 book ai didi

c++ - 什么时候为派生类初始化 vptr?

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:21 28 4
gpt4 key购买 nike

最近,我一直在阅读“inside the c++ object model”。它说 vptr 在调用基类的构造函数后初始化。所以我进行了测试:

class A {
public:
A(int i) {
std::cout << i << std::endl;
}
virtual int vfunc() {
return 1;
}
};

class B : public A {
public:
B() : A(vfunc()) {
}

virtual int vfunc() {
return 2;
}
};

int main() {
B b;
}

结果如下:

2

我的问题是,类 B 是否在调用基类 A 的构造函数之前先设置其 vptr?

最佳答案

您的问题的答案是。如果在父构造函数执行之前设置 vptr,则意味着该构造函数将覆盖它。

至于您在代码中看到的行为:在其构造函数内对正在构造的对象的虚函数的任何调用都是在没有 vptr 的情况下解析的。所以你的代码实际上等同于:

B() : A(B::vfunc()) {
}

没有虚拟通话。相关标准写法([class.cdtor]p3):

Member functions, including virtual functions (13.3), can be called during construction or destruction (15.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.

关于c++ - 什么时候为派生类初始化 vptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com