Initializer List Behavior: Differences in std::vector and std::array
While std::vector and std::array are both containers in C , their behavior with initializer lists differs. In this article, we'll explore the intricacies of aggregate initialization and understand why double curly braces are required for std::array.
Consider the following code snippet that initializes a std::vector and a std::array:
std::vector<int> x{1,2,3,4}; std::array<int, 4> y{{1,2,3,4}};
std::vector Initialization
std::vector supports user-defined constructors, including those that accept a std::initializer_list. Therefore, we can directly initialize x using braces without the need for extra curly braces.
std::array Initialization
Unlike std::vector, std::array is an aggregate that doesn't have user-defined constructors. Instead, it relies on aggregate initialization, a feature inherited from C.
In "old style" aggregate initialization, the equal sign and colons are used:
std::array<int, 4> y = { { 1, 2, 3, 4 } };
However, when using direct list initialization (introduced in C 11), this = syntax is no longer valid. Additionally, brace elision, which allows omitting extra braces, is only permitted in declarations with the old style = syntax. For direct list initialization, extra braces are mandatory.
CWG Defect
A CWG defect report (CWG defect #1270) aims to resolve this restriction by allowing brace elision for other forms of list initialization. If adopted, the following code would be well-formed:
std::array<int, 4> y{ 1, 2, 3, 4 };
In conclusion, the difference in behavior between std::vector and std::array with initializer lists stems from their fundamental characteristics as a class with user-defined constructors and an aggregate relying on aggregate initialization, respectively. Double curly braces are required for std::array to conform to the rules of aggregate initialization, while std::vector allows for direct initialization using a single set of braces without relying on old-style aggregate initialization syntax.
The above is the detailed content of Why Does `std::array` Require Double Curly Braces in Initializer Lists?. For more information, please follow other related articles on the PHP Chinese website!