c++ - 需要对 C++11 标准中的 8.5.p7 进行一些说明

标签 c++ c++11 initialization

C++11 标准第 8.5p7 段规定:

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

  • if T is an array type, then each element is value-initialized;

  • otherwise, the object is zero-initialized.

我无法理解上面的粗体字符。 T 的隐式默认构造函数的额外调用如何改变在这种情况下刚刚发生的零初始化?

最佳答案

这是一个具体的例子:

class A {
    int a;
public:
    A() : a(1) {}
};

class B {
    int b;
    A c;
};

B 属于这一类——它是一种非 union 类类型,没有用户提供的构造函数。所以如果一个 B 是值初始化的,它首先会被初始化为零(所以 bc.a 都将被设置为 0),然后会调用默认构造函数(会调用A的构造函数并将c.a设置为1)。

通过 as-if 规则,这些可能会被优化器组合成一个步骤(这会将 b 设置为 0 和 c.a 到 1),因为没有人可以看到零初始化和默认构造函数之间的对象。

关于c++ - 需要对 C++11 标准中的 8.5.p7 进行一些说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17733432/

相关文章:

c - 为什么设置( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ldl")不起作用?

c++ - std::uniform_real_distribution<double>(0,1) 能否返回大于 0.99999999999999994 的值?

swift - 为什么 Swift 不允许在 class init 中给 self 赋值,而在 protocol init 中却不允许?

c++ - 从变量初始化数组 (C++)

c++ - 枚举与宏状态 C++

c++ - 使用 ofstream 创建一个位图文件有一个奇怪的输出

c++ - 访问静态和非静态的模板构造函数和函数

c++ - printf 与 long long int 的结果不一致?

c++ - 如何任意排序元组的类型?

c++ - 未知类型的可变参数构造函数参数列表