簡體   English   中英

C++11:正確的 std::array 初始化?

[英]C++11: Correct std::array initialization?

如果我按如下方式初始化 std::array,編譯器會給我一個關於缺少大括號的警告

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 版本中的一個錯誤,還是故意這樣做的? 如果是這樣,為什么?

這是std::array的裸實現:

template<typename T, std::size_t N>
struct array {
    T __array_impl[N];
};

它是一個聚合結構,其唯一的數據成員是傳統數組,因此內部{}用於初始化內部數組。

在聚合初始化的某些情況下允許大括號省略(但通常不推薦),因此在這種情況下只能使用一個大括號。 請參見此處: C++ 數組向量

根據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"} };

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 =

std::array 參考

C++17 std::array類模板參數推導(CTAD)

這個新的 C++17 特性標准庫使用,現在允許我們省略模板類型,以便以下工作:

主程序

#include <array>

int main() {
    std::array a{1, 2, 3};
}

而不是std::array<int, 3> a{1, 2, 3};

測試:

g++ -ggdb3 -O0 -std=c++17 -Wall -Wextra -pedantic -o main.out main.cpp

例如,如果我們設置-std=c++14 ,它將無法編譯:

error: missing template arguments before ‘a’

另請參閱: 推斷 std::array 大小?

在 Ubuntu 18.04、GCC 7.5.0 上測試。

我認為您可以簡單地使用以下內容,

std::array <int, 6> numbers {0};
numbers[3] = 1;
std::ranges::copy(numbers,  std::ostream_iterator<int>(std::cout, ','));
numbers = {0};
std::cout << "\n";
std::ranges::copy(numbers,  std::ostream_iterator<int>(std::cout, ','));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM