Why do clang and gcc handle fixed initialization of structures with initialization in the class differently?

I recently discovered weird clang and gcc behavior. I have a struct ( MyClass ) that uses class initialization for one of its members ( active ):

 struct MyClass { int something; bool active = true; }; 

Now I am trying to copy the initialization of this class.

Using clang, I can decide whether I include active in the initializer list ( MyClass a = { 42, true}; ) or not ( MyClass a = { 42 }; ).

However, using gcc, my code compiles if I do not enable active . Otherwise, I will get the following compiler error:

  error: could not convert '{42, true}' from '<brace-enclosed initializer list>' to 'MyClass' 

This is mistake? What does the standard say about this? What about VSC ++? Which method would you recommend as a portable solution?

Tested using gcc 4.9 and clang 3.5 on Debian Linux.

+6
source share
1 answer

The behavior of this code has changed between C ++ 11 and C ++ 14.

In C ++ 11, the presence of = true means that the class was not an aggregate. Therefore, you cannot use aggregate initialization.

In C ++ 14, the class is still an aggregate, so you can use aggregate initialization again.

The difference between compilers can be explained by the fact that it is newer than the other. Using compiler explorer , I see that gcc 4.9.x is wrong, but this is fixed in gcc 5.1.

+8
source

All Articles