测试 t=测试(); C++98 中会发生什么?

Test t=Test(); what happens in C++98?

考虑以下程序:

#include <iostream>
struct Test
{
    int a;
};
int main()
{
    Test t=Test();
    std::cout<<t.a<<'\n';
}

Test t=Test(); 值初始化一个临时值并复制初始化它。 (大多数编译器优化了复制操作(来源:value initialization))。但是值初始化是由C++03引入的。执行 Test t=Test();C++98 会发生什么?是否保证我会在任何 C++98 编译器上得到 0 作为输出(在本例中为 t.a 的值)? .是否在 C++98 中执行默认初始化?

C++ 标准 (1998)

[dcl.fct.def]

7 An object whose initializer is an empty set of parentheses, i.e., (), shall be default-initialized.

[dcl.init]

5 To zero-initialize storage for an object of type T means:

— if T is a scalar type (3.9), the storage is set to the value of 0 (zero) converted to T;

— if T is a non-union class type, the storage for each nonstatic data member and each base-class subobject is zero-initialized;

— if T is a union type, the storage for its first data member 89) is zero-initialized;

— if T is an array type, the storage for each element is zero-initialized;

— if T is a reference type, no initialization is performed.

To default-initialize an object of type T means:

— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

otherwise, the storage for the object is zero-initialized.

似乎临时初始化是默认的,这意味着 POD 类型(Test 是)的零初始化,因此 t.a == 0 是有保证的。

从 C++03 开始​​,这是值初始化并且保持相同的保证。

似乎在 C++03 中添加值初始化和 re-definition 默认初始化是不允许 zero-initializing 标量和 POD 类型(在某些情况下)。