Why is the C++ initializer_list behavior for std::vector and std::array different?(为什么 std::vector 和 std::array 的 C++ initializer_list 行为不同?)
问题描述
代码:
std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};
为什么 std::array 需要双花括号?
Why do I need double curly braces for std::array?
推荐答案
std::array 是一个聚合:它没有任何用户声明的构造函数,甚至没有一个采用 std::initializer_list.使用大括号进行初始化是使用聚合初始化来执行的,这是从 C 继承的 C++ 特性.
std::array<T, N> is an aggregate: it doesn't have any user-declared constructors, not even one taking a std::initializer_list. Initialization using braces is performed using aggregate initialization, a feature of C++ that was inherited from C.
聚合初始化的旧风格"使用=:
The "old style" of aggregate initialization uses the =:
std::array<int, 4> y = { { 1, 2, 3, 4 } };
使用这种老式的聚合初始化,额外的大括号可能会被省略,所以这相当于:
With this old style of aggregate initialization, extra braces may be elided, so this is equivalent to:
std::array<int, 4> y = { 1, 2, 3, 4 };
然而,这些额外的大括号只能在T x = { a };"形式的声明中被省略(C++11 §8.5.1/11),也就是说,当使用旧样式 = 时.这条允许大括号省略的规则不适用于直接列表初始化.这里的脚注是:在列表初始化的其他用途中不能省略大括号."
However, these extra braces may only be elided "in a declaration of the form T x = { a };" (C++11 §8.5.1/11), that is, when the old style = is used . This rule allowing brace elision does not apply for direct list initialization. A footnote here reads: "Braces cannot be elided in other uses of list-initialization."
有关于此限制的缺陷报告:CWG 缺陷 #1270.如果提议的决议获得通过,则其他形式的列表初始化将允许省略大括号,以下内容将是良构的:
There is a defect report concerning this restriction: CWG defect #1270. If the proposed resolution is adopted, brace elision will be allowed for other forms of list initialization, and the following will be well-formed:
std::array<int, 4> y{ 1, 2, 3, 4 };
(感谢 Ville Voutilainen 找到缺陷报告.)
(Hat tip to Ville Voutilainen for finding the defect report.)
这篇关于为什么 std::vector 和 std::array 的 C++ initializer_list 行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::vector 和 std::array 的 C++ initializer_list 行为不同?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
