c++ - 在 C++ 中是否允许从括号值列表中赋值 std::array?

标签 c++ arrays c++11 language-lawyer

在 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/

相关文章:

c++通过参数将值传递给char数组

c++ - SSE Intrinsics 和循环展开

c++ - 如果用户使用 Rice 在 Ruby 中重新定义 initialize(),则避免 C++ 代码中的段错误

arrays - Delphi - 检查元素是否在 TArray<string> 中存在两次

Java,二维数组排序

arrays - 创建不同长度的 3 维数组

c++ - friend 模板特化声明中不允许使用 Consexpr?

c++ - 对齐对 C++11 中的性能真的很重要吗?

c++ - 在模板类中为特定类型编写比较函数

c++ - 使用自定义凭据提供程序的远程桌面连接