std::array;初始化

发布于 2024-12-27 12:01:16 字数 332 浏览 1 评论 0原文

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 structs 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空心↖ 2025-01-03 12:01:17

好处是您需要输入的内容更少。但缺点是只有当声明具有这种形式时才允许省略大括号。如果省略 =,或者如果数组是成员并且使用 member{{1, 2, 3, 4, 5}} 初始化它,则不能只传递一对牙套。

这是因为,当将大括号传递给函数时,人们担心可能会出现重载歧义,如 f({{1, 2, 3, 4, 5}}) 中。但它引起了一些讨论,并生成了一份问题报告。

本质上, = { ... } 初始化始终能够省略大括号,如

int a[][2] = { 1, 2, 3, 4 };

That's not new 中所示。新功能是您可以省略 =,但必须指定所有大括号

int a[][2]{ {1, 2}, {3, 4} };

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 with member{{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 in

int a[][2] = { 1, 2, 3, 4 };

That's not new. What is new is that you can omit the =, but then you must specify all braces

int a[][2]{ {1, 2}, {3, 4} };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文