gpt4 book ai didi

c++ - 初始化真的需要花括号吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:37 25 4
gpt4 key购买 nike

根据 GCC 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5),我在以下代码的数组初始化中缺少花括号:

#include <iostream>
#include <boost/array.hpp>
#include <array>

int main(){
int plain[] = {1,2,3,4,5};
std::array <int, 5> std_arr = {1,2,3,4,5}; // warning, see below
boost::array<int, 5> boost_arr = {1,2,3,4,5}; // warning, see below
std::cout << plain[0] << std_arr[1] << boost_arr[2] << std::endl;
}
> g++ test.cc -Wall -Wextra -pedantic --std=c++0x                                                                                  test.cc: in function »int main()«:test.cc:7:47: warning: curly braces missing around initialization for »std::array::value_type [5] {aka int [5]}« [-Wmissing-braces]test.cc:8:47: warning: curly braces missing around initialization for »int [5]« [-Wmissing-braces]

显然(GCC missing braces around initializer)这是 GCC 中的一个错误,即使在稍微不同的上下文中也是如此。答案不同于“提交错误报告”和“只是禁用警告”。

但是,在 std::arrayboost::array 的上下文中,这个警告是多余的,还是我遗漏了一些重要的东西?

(我可能会添加额外的大括号而不是禁用警告,但我很好奇其含义)

最佳答案

我认为这已经得到解答 here .

std::array is funny. It is defined basically like this:

template struct std::array { T a[size]; };

It is a struct which contains an array. It does not have a constructor that takes an initializer list. But std::array is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array inside the struct, you need a second set of curly braces:

std::array strings = {{ "a", "b" }};

Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.

我相信它可能与 this defect 有关,已在几个问题中链接。

这是一个 answer regarding it :

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

我注意到这个错误没有出现在 gcc 4.8.1 中,但它出现在一个非常旧的版本 (4.4.7) 上,我认为这是补丁(因为 defect 提出解决方案日期为 2012 年 2 月,此链接日期为 2012 年 3 月):

http://gcc.gnu.org/ml/gcc-patches/2012-03/msg00215.html

关于c++ - 初始化真的需要花括号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com