When using initializer lists for C containers, a perplexing difference arises between std::vector and std::array. Let's explore the reasons behind this behavior.
Problem:
Consider the following code:
std::vector<int> x{1,2,3,4}; std::array<int, 4> y{{1,2,3,4}};
Why is it necessary to use double curly braces for std::array but not for std::vector?
Answer:
The behavior stems from the nature of std::array
std::array<int, 4> y = { { 1, 2, 3, 4 } };
In this old style, extra braces may be omitted, resulting in the equivalent code:
std::array<int, 4> y = { 1, 2, 3, 4 };
However, this brace elision is only allowed when using the old style initialization with the = syntax. Direct list initialization, which does not use the = syntax, does not allow brace elision. This limitation is governed by C 11 §8.5.1/11.
Proposed Resolution:
A defect report (CWG defect #1270) has been raised to address this limitation. If the proposed resolution is adopted, brace elision will be allowed for all forms of list initialization, including the following:
std::array<int, 4> y{ 1, 2, 3, 4 };
This change would bring consistency to the behavior of std::vector and std::array when using initializer lists.
The above is the detailed content of Why does std::array require double curly braces for initializer lists while std::vector doesn't?. For more information, please follow other related articles on the PHP Chinese website!