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

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

问题描述

使用 C++11 std::array,我是否可以保证语法 std::array;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::arrayT[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_int 以及两种数组的所有成员都被初始化为零.

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

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

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