C++ 派生类在初始化之前调用基类的方法

标签 c++ language-lawyer

这是一个简单的程序,我很确定它有未定义的行为,但我想确定一下。

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::foovirtual 会发生什么变化吗?

最佳答案

这两种情况(包括虚拟成员函数)都是未定义的行为,如 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/

相关文章:

c++ - 在没有分配的情况下加入并重新拆分两个 std::list

c++ - Objective-c iOS 中的二维码生成器

c++ - QT-Graphics - 如何限制项目的移动

c++ - 使用 7Zlib 命令行将文件解压到目录中

c++ - 什么是执行宽字符集及其编码?

c - 为什么我不能检索我的灵活数组成员大小?

java - JLS 的哪一部分指定您不能从 List<?将 List<Superclass>> 扩展到 List<List<Subclass>>?

c++ - Stroustrup 如何对临时对象进行非常量引用?

c++ - 当重载函数作为参数涉及时,模板参数推导如何工作?

c++ - 循环链表 : How to correct my remove node function?