Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ gives strange error during structure initialization with an array inside

Tags:

c++

I try to compile very simple code:

struct T {
    int a[3];
    int b;
    int c;
};

int main() {
    const int as[3] = { 5, 6, 7, };
    const T t {
        as, 2, 3,
    };
    return 0;
}

But it gives me very strange errors:

t.cpp: In function 'int main()':
t.cpp:11:5: error: array must be initialized with a brace-enclosed initializer
     };
     ^

As from what I understand the compiler wants me to initialize everything in one single place. How do I initialize fields separately and then use them during initiliazation the structure later?

like image 459
Victor Polevoy Avatar asked Sep 14 '17 06:09

Victor Polevoy


2 Answers

Arrays are neither copy-constructible nor copy-assignable. If you have access to C++11 and newer, you could use std::array.

#include <array>

struct T {
    std::array<int, 3> a;
    int b;
    int c;
};

int main() {
    const std::array<int,3> as = { 5, 6, 7, };
    const T t {
        as, 2, 3,
    };
    return 0;
}

Otherwise you will have to roll a loop and copy the elements individually.

like image 81
DeiDei Avatar answered Oct 14 '22 10:10

DeiDei


C++ arrays are not copy constructible, so compilation will fail. However,

struct T {
    int a[3];
    int b;
    int c;
};

int main() {
    const T t {
        {5, 6, 7, }, 2, 3,
    };
    return 0;
}

is an alternative, although it does discard the explicit as variable.

Reference: http://en.cppreference.com/w/cpp/concept/CopyConstructible

like image 32
Bathsheba Avatar answered Oct 14 '22 10:10

Bathsheba