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::vectorx{1,2,3,4}; std::array 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::arrayy = { { 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::arrayy{ 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3