Home > Backend Development > C++ > Why Does `std::array` Require Double Curly Braces for Initialization, While `std::vector` Only Needs Single Curly Braces?

Why Does `std::array` Require Double Curly Braces for Initialization, While `std::vector` Only Needs Single Curly Braces?

Barbara Streisand
Release: 2024-11-07 07:30:03
Original
522 people have browsed it

Why Does `std::array` Require Double Curly Braces for Initialization, While `std::vector` Only Needs Single Curly Braces?

Initializer List Behavior Difference in std::vector and std::array

In C , the initializer_list behavior for std::vector and std::array differs significantly. Consider the following code snippets:

std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};
Copy after login

Why does std::array require double curly braces, while std::vector only requires single curly braces?

Explanation

std::vector has a user-defined constructor that takes a std::initializer_list as an argument. This allows for direct list initialization using single curly braces.

On the other hand, std::array is an aggregate type that does not have any user-defined constructors. Instead, it uses aggregate initialization, a feature inherited from C. Aggregate initialization allows for initialization using double curly braces.

The older syntax for aggregate initialization using braces and the = sign is also valid:

std::array<int, 4> y = { { 1, 2, 3, 4 } };
Copy after login

However, this syntax allows for brace elision in certain cases, which is not permitted for direct list initialization with std::array. A footnote in the C standard (C 11 §8.5.1/11) states that "Braces cannot be elided in other uses of list-initialization."

Defect Report and Proposed Resolution

A defect report (CWG defect #1270) has been filed to address this restriction. If the proposed resolution is adopted, brace elision will be allowed for std::array direct list initialization, making the following valid:

std::array<int, 4> y{ 1, 2, 3, 4 };
Copy after login

The above is the detailed content of Why Does `std::array` Require Double Curly Braces for Initialization, While `std::vector` Only Needs Single Curly Braces?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template