使用花括号构造`std::array`,其中包含比其可以容纳的元素少的元素?

huangapple go评论81阅读模式
英文:

Constructing a `std::array` with braces containing fewer elements than it can hold?

问题

如果我使用花括号构造一个std::array<T, N>,并且提供少于N个项目,那些项目会被零初始化吗?(还是它们会保持默认初始化?)如果我给它零个项目(即= {}),那我认为它会将所有元素都置零。

我找不到这个简单问题的明确答案。由于std::array在像std::array<int, 2> x = { 1 };这样的情况下使用聚合初始化,因此需要查看 https://en.cppreference.com/w/cpp/language/aggregate_initialization 上的聚合初始化规则。在那里,我只看到与此情况相关的一句话是:“如果指定了数组的大小并且它大于字符串文字中的字符数,则剩余的字符将被零初始化。”但这是在“字符数组”部分,因此似乎不是普遍适用的。另一方面,使用constexrp作为未定义行为检测器表明它们被置零:https://godbolt.org/z/zE9xKvbrq

相关链接:

英文:

If I construct a std::array<T, N> with braces and give it fewer than N items, are those items zero-initialized? (Or are they left default-initialized?) If I give it zero items (i.e., = {}) then I believe it zero-initializes all elements.

I can't find an explicit answer to this simple question. Since std::array uses aggregate initialization when used like std::array<int, 2> x = { 1 };, that leads to https://en.cppreference.com/w/cpp/language/aggregate_initialization for rules on aggregate initialization. There, the only mention I see of this case is "If the size of the array is specified and it is larger than the number of characters in the string literal, the remaining characters are zero-initialized." but that's in the "Character arrays" section, so seems like it's not generally true. On the other hand, using constexrp as a UB detector indicates that they are zero'd: https://godbolt.org/z/zE9xKvbrq

Related:

答案1

得分: 7

聚合初始化会将那些没有其他初始化器的元素置零(准确来说是进行值初始化)。

[dcl.init.aggr]/5.2

对于非联合体的聚合体,每个没有明确初始化的元素的初始化如下:

— 如果该元素具有默认成员初始化器([class.mem]),则从该初始化器初始化该元素。

— 否则,如果该元素不是引用,则从空初始化列表([dcl.init.list])进行复制初始化。

— 否则,程序是非法的。

英文:

Aggregate initialization zeroes (value-initializes, to be exact) the elements that don't otherwise have initializers.

[dcl.init.aggr]/5.2

> For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:
>
> — If the element has a default member initializer ([class.mem]), the element is initialized from that initializer.
>
> — Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]).
>
> — Otherwise, the program is ill-formed.

huangapple
  • 本文由 发表于 2023年7月11日 02:23:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定