C++11:正确的 std::array 初始化? [英] C++11: Correct std::array initialization?

查看:55
本文介绍了C++11:正确的 std::array 初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我按如下方式初始化 std::array,编译器会警告我缺少大括号

If I initialize a std::array as follows, the compiler gives me a warning about missing braces

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

这解决了问题:

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

这是警告信息:

missing braces around initializer for 'std::array<int, 4u>::value_type [4] {aka int [4]}' [-Wmissing-braces]

这只是我的 gcc 版本中的一个错误,还是故意这样做的?如果是,为什么?

Is this just a bug in my version of gcc, or is it done intentionally? If so, why?

推荐答案

这是 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.

在聚合初始化的某些情况下允许大括号省略(但通常不推荐),因此在这种情况下只能使用一个大括号.请参见此处:C++ 数组向量

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++11:正确的 std::array 初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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