lundi 28 décembre 2015

Why do clang and gcc handle braced-initialization of structs with in-class initialization differently?

I recently discovered an odd behavior of clang and gcc. I have a struct (MyClass) which uses in-class initialization for one of its members (active):

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

Now I try to brace-initialize 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 only compiles if I do not include active. Else, I will get the following compiler error:

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

Is this a bug? What does the standard say about it? What about VSC++? Which way would you recommend as the portable solution?

Tested using gcc 4.9 and clang 3.5 on Debian Linux.

Aucun commentaire:

Enregistrer un commentaire