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
是值初始化的,它首先会被初始化为零(所以 b
和 c.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/