Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c++ - g++ 4.9 rejects valid aggregate initialization in C++14

Consider this code:

struct S
{
    int x;
    double y = 1.1;
};

int main()
{
    S s = {0};
}

According to the C++14 standard, § 8.5.1/7

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equal- initializer, from an empty initializer list (8.5.4).

the code should be perfectly valid.

However, g++ 4.9.2 rejects the code (compiled with -std=c++14)

so.cpp:9:13: error: could not convert '{0}' from '<brace-enclosed initializer list>' to 'S'
     S s = {0};

clang++ on the other hand compiles it.

Is this a known issue for g++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are correct, this is valid C++14; however, in C++11 a class with in class member initializers was not an aggregate and so this is not valid in C++11.

The issue as I noted in my answer to the above question and I realized later after I made my initial comment is that gcc did not support this change until 5.0 (see it live):

G++ now supports C++14 aggregates with non-static data member initializers.

struct A { int i, j = i; };
A a = { 42 }; // a.j is also 42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...