为什么std :: vector和std :: array的C ++ initializer_list行为不同? [英] Why is the C++ initializer_list behavior for std::vector and std::array different?

查看:264
本文介绍了为什么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的双花括号?

解决方案

std :: array< T,N> 是一个聚合: -declared构造函数,甚至没有一个采取 std :: initializer_list 。使用大括号的初始化是使用继承自C的C ++的一个特性 来执行。



聚合初始化的旧样式 =

  std :: array< int,4> y = {{1,2,3,4}}; 

使用这种旧式的聚合初始化,可能会省略额外的大括号, / p>

  std :: array< int,4> y = {1,2,3,4}; 

但是,这些额外的大括号只能在形式 T x = {a}; (C ++ 11§8.5.1/ 11),也就是说,当旧样式 = 用来 。允许括号删除的此规则不适用于直接列表初始化。这里的脚注如下:大括号不能在列表初始化的其他使用中省略。

有关此限制的缺陷报告:CWG缺陷#1270 。如果采纳建议的决议,则允许其他形式的列表初始化,并且以下将是良好的形式:

  std :: array< int,4> y {1,2,3,4}; 

(用于查找缺陷报告的帽子提示Ville Voutilainen。)


Code:

std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};

Why do I need double curly braces for std::array?

解决方案

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 };

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."

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 };

(Hat tip to Ville Voutilainen for finding the defect report.)

这篇关于为什么std :: vector和std :: array的C ++ initializer_list行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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