简体   繁体   中英

Brace-initialization of an array of structs in c++11

Here is my code:

#include <string>

struct A
{
    int a;
    std::string sa;
};

int main()
{
    A arr[3]{};
}

When I compile it with gcc 4.8.2 (on Ubuntu 14.04) with -std=gnu++11 option I get the following error:

example.cpp: In function ‘int main()’:
example.cpp:11:14: internal compiler error: in gimplify_init_constructor, at gimplify.c:4271
 A arr[3]{};
          ^

Why does it throw an internal compiler error? Is it a compiler bug?

An internal compiler error is always a compiler bug, and says nothing about whether the code is valid.

If the code is invalid, the compiler is supposed to give an error message telling you what's wrong with the code. An internal compiler error only tells you what's wrong with the compiler.

Given that this internal compiler error still exists in later versions (I just checked 4.9.2, as well as current sources as of January 29th), I would normally strongly encourage reporting this as a bug to the GCC developers, but a quick search reveals that it's already known to them .

You can work around it by writing A arr[3]{{}}; , which means the same thing. It contains the same initialiser for the first element of arr that it would already get by default.

I encountered the same issue right out of blue with gcc 4.8.5 when I added an std::string to a content of the array struct. Adding extra {} as suggested above helped. Maybe this can give a clue why this compiler error happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM