C++ derived class 在初始化之前调用 base class 上的方法
C++ derived class calls method on base class before initialization
这是一个简单的程序,我很确定它有未定义的行为,但我想确定一下。
struct A {
int x;
A(int y):x(y) {}
int foo() { return x; }
};
struct B : public A {
B():A(foo()) {}
};
我假设这具有未定义的行为,因为对 A::foo
的调用发生在构建 A
对象之前,并且它读取未初始化的 class 变量。
但是,如果 A::foo
的实现改为 { return 0; }
而不是 { return x; }
,即函数不访问 class 成员,它是否仍然未定义的行为?
进一步的问题 - 如果 A::foo
是 virtual
,有什么变化吗?
中所述,这在两种情况下都是未定义的行为(包括虚拟成员函数)
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.
此要点主要包含您提供的示例代码片段,并明确指出未定义的行为。
这是一个简单的程序,我很确定它有未定义的行为,但我想确定一下。
struct A {
int x;
A(int y):x(y) {}
int foo() { return x; }
};
struct B : public A {
B():A(foo()) {}
};
我假设这具有未定义的行为,因为对 A::foo
的调用发生在构建 A
对象之前,并且它读取未初始化的 class 变量。
但是,如果 A::foo
的实现改为 { return 0; }
而不是 { return x; }
,即函数不访问 class 成员,它是否仍然未定义的行为?
进一步的问题 - 如果 A::foo
是 virtual
,有什么变化吗?
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.
此要点主要包含您提供的示例代码片段,并明确指出未定义的行为。