Search code examples
c++arraysc++17member-initialization

Compiler error on member initialization of c-style array member (compared with std::array member)


I encountered this problem while initializing a member array variable (c-style). Interestingly converting the member into a std::array<> solves the problem. See below:

struct A {
  A(int aa) : a(aa) {}

  A(const A &a) = delete;
  A &operator=(const A &a) = delete;

private:
  int a;
  std::vector<int> v;
};

struct B1 {
  B1() : a1{{{1}, {2}}} {} // -> compiles OK (gcc 9.2)

private:
  std::array<A, 2> a1;
};

struct B2 {
  B2()
    : a2{{1}, {2}} // -> error: use of deleted function 'A::A(const A&)' (gcc 9.2)
  {} 

private:
  A a2[2];
};

Demo

My question is why is this difference in (compiler) behavior? I was assuming that functionality-wise they are pretty much the same (I understand std::array<> is more of an aggregate instead of a pure container, like vector - I might be wrong though).

Additional observation:

  • The compiler allows c-style array if I remove the vector<> member in A
  • GCC 9.5 does not raise any issues. Does it mean it's a GCC bug (I couldn't find anything on the release notes)?

Update:
It is a GCC bug: Brace initialization of array sometimes fails if no copy constructor (reported in 4.9 and resolved in 9.4)


Solution

  • Does it mean it's a GCC bug

    Yes, this seems to be a gcc bug that has been fixed in gcc 9.4. Demo.

    A bug for the same has been submitted as:

    GCC rejects valid program involving initialization of array in member initializer list