为什么我需要一个类似于复合文字的临时构造来初始化我的std::数组成员

Why do I need a compound literal like temporary construction to initialise my std::array member?

本文关键字:我的 组成员 数组 std 初始化 文字 复合 类似于 一个 为什么      更新时间:2023-10-16

考虑这个最小的例子:

#include <array>
struct X {
  std::array<int,2> a;
  X(int i, int j) : a(std::array<int,2>{{i,j}}) {}
  //                 ^^^^^^^^^^^^^^^^^^       ^
};

根据其他帖子,在这种情况下,我不应该明确地构建一个临时的。我应该能够写:

  X(int i, int j) : a{{i,j}} {}

但我尝试过的这个版本和其他几个(类似的)版本都被我的g++4.5.2拒绝了。我目前只有一个用于实验。上面写着:

error: could not convert ‘{{i, j}}’ to ‘std::array<int, 2ul>’

这是编译器实现的限制还是发生了什么?

很多时候,问题在于编译器版本。以下代码适用于GCC 4.7.1:

#include <array>
struct X{
  std::array<int, 2> a;
  X() : a{{1,2}} {}
};
int main(){
  X x;
}

活生生的例子。