gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:07:17 33 4
gpt4 key购买 nike

考虑以下程序:

#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.初始化]

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 中添加值初始化和默认初始化的重新定义似乎是为了允许不对标量和 POD 类型进行零初始化(在某些情况下)。

关于c++ - 测试 t=测试(); C++98 中会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34856965/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com