英文:
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
相关链接:
- https://stackoverflow.com/questions/18295302/default-initialization-of-stdarray
- https://stackoverflow.com/questions/14178264/c11-correct-stdarray-initialization
- https://stackoverflow.com/questions/8192185/using-stdarray-with-initialization-lists
- https://stackoverflow.com/questions/6114067/how-to-emulate-c-array-initialization-int-arr-e1-e2-e3-behaviou
英文:
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:
- https://stackoverflow.com/questions/18295302/default-initialization-of-stdarray
- https://stackoverflow.com/questions/14178264/c11-correct-stdarray-initialization
- https://stackoverflow.com/questions/8192185/using-stdarray-with-initialization-lists
- https://stackoverflow.com/questions/6114067/how-to-emulate-c-array-initialization-int-arr-e1-e2-e3-behaviou
答案1
得分: 7
聚合初始化会将那些没有其他初始化器的元素置零(准确来说是进行值初始化)。
对于非联合体的聚合体,每个没有明确初始化的元素的初始化如下:
— 如果该元素具有默认成员初始化器([class.mem]),则从该初始化器初始化该元素。
— 否则,如果该元素不是引用,则从空初始化列表([dcl.init.list])进行复制初始化。
— 否则,程序是非法的。
英文:
Aggregate initialization zeroes (value-initializes, to be exact) the elements that don't otherwise have initializers.
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论