gpt4 book ai didi

c++ - 数字类型的大括号初始化。它们是0初始化的吗?

转载 作者:可可西里 更新时间:2023-11-01 18:19:52 26 4
gpt4 key购买 nike

我想确定以下内容

int i{};
double x{};

将所有变量初始化为 0。我的编译器似乎在所有模式下都这样做,但我需要确保标准明确说明了这一点。

欢迎任何对 C++11 标准的引用。

最佳答案

这是标准规定的(所有引自 N3337)。

T x{};列表初始化

[dcl.init.list]/1: List-initialization is initialization of an object or reference from a braced-init-list.Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. [...]

列表初始化的适用定义:

[dcl.init.list]/3: List-initialization of an object or reference of type T is defined as follows:

  • [lots of non-applicable rules]
  • Otherwise, if the initializer list has no elements, the object is value-initialized.

所以内置类型的形式是值初始化:

[dcl.init]/7: To value-initialize an object of type T means:

  • [non-applicable rules]
  • otherwise, the object is zero-initialized.

所以现在我们正在寻找零初始化(是的,C++ 有很多类型的初始化):

[dcl.init]/5: To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
  • [...]

是的,因为算术类型是标量类型([basic.types]/9 如果你不相信我的话),这些形式都用 0 初始化它们的对象.

关于c++ - 数字类型的大括号初始化。它们是0初始化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913572/

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