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 行为不同?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01