在 c++ primer(第 5 版)中,提到不允许从花括号值列表赋值 std::array。
Because the size of the right-hand operand might differ from the size of the left-hand operand, the array type does not support assign and it does not allow assignment from a braced list of values.
下面的代码作为例子给出。
std::array<int, 10> a1 = {0,1,2,3,4,5,6,7,8,9};
std::array<int, 10> a2 = {0}; // elements all have value 0
a1 = a2; // replaces elements in a1
a2 = {0}; // error: cannot assign to an array from a braced list
但是,当我编译这个 code使用 c++11 编译器它工作正常。现在允许这样做还是我遗漏了什么?
最佳答案
是的,std::array
可以从花括号列表中赋值。它只是在 C++11 规则下正常工作——类不需要做任何特殊的事情来支持它。 Consider :
struct S {int x; int y;};
int main() {
S s{1, 2};
s = {3, 4};
}
作为聚合,S
可以从大括号初始化列表构造。此外,S
有一个隐式声明的赋值运算符采用 const S&
。将两者放在一起,编译器将 s = {3, 4}
解释为 s.operator=(S{3, 4})
std::array
也是如此。
关于c++ - 在 C++ 中是否允许从括号值列表中赋值 std::array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734492/