C++11:正确的 std::array 初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14178264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++11: Correct std::array initialization?
提问by Byzantian
If I initialize a std::array as follows, the compiler gives me a warning about missing braces
如果我按如下方式初始化 std::array,编译器会给我一个关于缺少大括号的警告
std::array<int, 4> a = {1, 2, 3, 4};
This fixes the problem:
这解决了这个问题:
std::array<int, 4> a = {{1, 2, 3, 4}};
This is the warning message:
这是警告消息:
missing braces around initializer for 'std::array<int, 4u>::value_type [4] {aka int [4]}' [-Wmissing-braces]
Is this just a bug in my version of gcc, or is it done intentionally? If so, why?
这只是我的 gcc 版本中的一个错误,还是故意完成的?如果是这样,为什么?
采纳答案by Pubby
This is the bare implementation of std::array
:
这是的裸实现std::array
:
template<typename T, std::size_t N>
struct array {
T __array_impl[N];
};
It's an aggregate struct whose only data member is a traditional array, such that the inner {}
is used to initialize the inner array.
它是一个聚合结构,其唯一的数据成员是传统数组,因此内部{}
用于初始化内部数组。
Brace elision is allowed in certain cases with aggregate initialization (but usually not recommended) and so only one brace can be used in this case. See here: C++ vector of arrays
在聚合初始化的某些情况下允许大括号省略(但通常不推荐),因此在这种情况下只能使用一个大括号。请参见此处:C++ 数组向量
回答by Draco Ater
According to cppreference. Double braces are required only if =
is omitted.
根据cppreference。仅当=
省略时才需要双大括号。
// construction uses aggregate initialization
std::array<int, 3> a1{ {1,2,3} }; // double-braces required
std::array<int, 3> a2 = {1, 2, 3}; // except after =
std::array<std::string, 2> a3 = { {std::string("a"), "b"} };
回答by Amit G.
Double-braces required in C++11 prior to the CWG 1270 (not needed in C++11 after the revision and in C++14 and beyond):
CWG 1270 之前的 C++11 中需要双大括号(修订后的 C++11 和 C++14 及更高版本中不需要):
// construction uses aggregate initialization
std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 prior to the CWG 1270 revision
// (not needed in C++11 after the revision and in C++14 and beyond)
std::array<int, 3> a2 = {1, 2, 3}; // never required after =