默认初始化std :: array? [英] Default initialization of std::array?

查看:467
本文介绍了默认初始化std :: array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C ++ 11 std::array,我是否可以保证语法std::array<T, N> x;将默认初始化数组的所有元素?

With C++11 std::array, do I have the guarantee that the syntax std::array<T, N> x; will default-initialize all the elements of the array ?

编辑:如果没有,是否有一种语法可以在所有数组(包括零尺寸数组)上使用,以将所有元素初始化为其默认值?

EDIT: if not, is there a syntax that will work on all arrays (including zero-sized arrays) to initialize all elements to their default value?

编辑:在 cppreference 上,默认构造函数说明说:

EDIT: on cppreference, the default constructor description says:

(constructor) (implicitly declared) (public member function)
default-constructs or copy-constructs every element of the array 

所以答案可能是肯定的.但我想根据标准或将来的标准来确定这一点.

so the answer may be yes. But I would like to be sure of that according to the standard or future standard.

推荐答案

根据定义,默认初始化是未指定其他初始化时发生的初始化; C ++语言保证您未为其提供显式初始化程序的 any 对象将被默认初始化(C ++ 11§8.5/11).其中包括类型为std::array<T, N>T[N]的对象.

By definition, default initialization is the initialization that occurs when no other initialization is specified; the C++ language guarantees you that any object for which you do not provide an explicit initializer will be default initialized (C++11 §8.5/11). That includes objects of type std::array<T, N> and T[N].

请注意,有一些类型的默认初始化无效,并且使对象的值不确定:任何非类,非数组类型(第8.5/6节).因此,具有此类类型的对象的默认初始化数组将具有不确定的值,例如:

Be aware that there are types for which default initialization has no effect and leaves the object's value indeterminate: any non-class, non-array type (§8.5/6). Consequently, a default-initialized array of objects with such types will have indeterminate value, e.g.:

int plain_int;
int c_style_array[13];
std::array<int, 13> cxx_style_array;

c样式数组和std::array都填充有不确定值的整数,就像plain_int具有不确定值一样.

Both the c-style array and std::array are filled with integers of indeterminate value, just as plain_int has indeterminate value.

是否有一种语法可用于所有数组(包括大小为零的数组),以将所有元素初始化为其默认值?

Is there a syntax that will work on all arrays (including zero-sized arrays) to initialize all elements to their default value?

我猜想,当您说至其默认值"时,您的意思是将所有元素初始化为T{}".不是默认初始化,而是值初始化(8.5/7).您可以在C ++ 11中通过为每个声明提供一个空的初始化程序来轻松地请求值初始化:

I'm guessing that when you say "to their default value" you really mean "initialize all elements to T{}". That's not default-initialization, it is value-initialization (8.5/7). You can request value initialization quite easily in C++11 by giving each declaration an empty initializer:

int plain_int{};
int c_style_array[13]{};
std::array<int, 13> cxx_style_array{};

这将依次对所有数组元素进行值初始化,从而导致plain_old_int以及两种数组的所有成员均被初始化为零.

Which will value-initialize all of the array elements in turn, resulting in plain_old_int, and all the members of both kinds of arrays, being initialized to zero.

这篇关于默认初始化std :: array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆