这是一个简单的程序,我很确定它有未定义的行为,但我想确定一下。
struct A {
int x;
A(int y):x(y) {}
int foo() { return x; }
};
struct B : public A {
B():A(foo()) {}
};
我假设这具有未定义的行为,因为对 A::foo
的调用发生在 A
对象构造之前,并且它读取未初始化的类变量.
但是,如果将A::foo
的实现更改为{ return 0; }
而不是 { return x; }
,即函数不访问类成员,这仍然是未定义的行为吗?
进一步的问题 - 如果 A::foo
是 virtual
会发生什么变化吗?
最佳答案
这两种情况(包括虚拟成员函数)都是未定义的行为,如 class.base.init 中指定的那样。 :
Member functions (including virtual member functions, [class.virtual]) can be called for an object under construction... 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 program has undefined behavior.
此要点实质上包含您提供的示例代码片段,并明确指出了未定义的行为。
关于C++ 派生类在初始化之前调用基类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62013510/