std::array;初始化
std::array
本质上是封装在 struct
中的 C 风格数组。 struct 的初始化需要大括号,数组的初始化也需要大括号。所以我需要两对大括号:
std::array<int, 5> a = {{1, 2, 3, 4, 5}};
但是我见过的大多数示例代码只使用一对大括号:
std::array<int, 5> b = {1, 2, 3, 4, 5};
为什么这是允许的,与第一种方法相比,它有什么优点或缺点?
A std::array<T>
is essentially a C-style array wrapped in a struct
. The initialization of struct
s requires braces, and the initialization of arrays requires braces as well. So I need two pairs of braces:
std::array<int, 5> a = {{1, 2, 3, 4, 5}};
But most of the example code I have seen only uses one pair of braces:
std::array<int, 5> b = {1, 2, 3, 4, 5};
How come this is allowed, and does it have any benefits or drawbacks compared to the first approch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好处是您需要输入的内容更少。但缺点是只有当声明具有这种形式时才允许省略大括号。如果省略
=
,或者如果数组是成员并且使用member{{1, 2, 3, 4, 5}}
初始化它,则不能只传递一对牙套。这是因为,当将大括号传递给函数时,人们担心可能会出现重载歧义,如
f({{1, 2, 3, 4, 5}})
中。但它引起了一些讨论,并生成了一份问题报告。本质上,
= { ... }
初始化始终能够省略大括号,如That's not new 中所示。新功能是您可以省略
=
,但必须指定所有大括号The benefit is that you have ... less to type. But the drawback is that you are only allowed to leave off braces when the declaration has that form. If you leave off the
=
, or if the array is a member and you initialize it withmember{{1, 2, 3, 4, 5}}
, you cannot only pass one pair of braces.This is because there were worries of possible overload ambiguities when braces are passed to functions, as in
f({{1, 2, 3, 4, 5}})
. But it caused some discussion and an issue report has been generated.Essentially, the
= { ... }
initialization always has been able to omit braces, as inThat's not new. What is new is that you can omit the
=
, but then you must specify all braces