According to the question std::array c++11 initializer syntax error It is not allowed to assign braced list to std::array in such way:
std::array<int, 10> a = {0,1,2,3,4,5,6,7,8,9};
a = {0}; // error: cannot assign to an array from a braced list
But actually I can not reproduce this error anymore. My GCC version is 4.8.2. Here is the code:
#include <array>
int main() {
std::array<int, 10> a;
a = {1};
return 0;
}
It compiles and executes without any error.
So, the question is, am I doing something wrong here? Or was there any changes that led to such behavior change?
The expression a = {1};
corresponds to case (10) of copy-list-initialization (see here). So, it should be correct according to the standard.
The problem you encountered may have something to do with the following change from C++11 to C++14: In C++11, when performing aggregate initialization, braces around nested initializer lists may only be elided if the syntax ... = {...}
is used, but not ...{...}
. In C++14, the latter is also allowed. See here for details. Now, assume C++11, should a = {1};
be correct or not? I think the answer depends on how you interpret the standard. Clearly, {1}
is used to initialize the second operand of operator=
. Following are two possible explanations that, respectively, give a positive answer and a negative one.
Explanation for a positive answer: The syntax ... = {...}
performs copy-list-init while ...{...}
performs direct-list-init. So, what the standard says is that brace elision is allowed in copy-list-init but not direct-list-init. a = {1};
performs copy-list-init. So the elision is OK.
Explanation for a negative answer: Just give the standard a literal interpretation. Elision is OK with the appearance of an equal sign, and not otherwise. In a = {1};
, initialization of the operand of operator=
is implicit without an equal sign. So, it is not OK. The statement here seems to suggest this verbatim explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With