Constructor interferes with member variable designated initializer?

  • A+
Category:Languages

For a while now, one has been able to use "designated initializer" in GCC:

struct CC{     double a_;     double b_; };  CC cc{.a_ = 1., .b_ = 2.}; assert(cc.a_ == 1. and cc.b_ == 2.); // ok CC cc{.bla = 0., .bli = 0.}; // compile error 

However when I add a constructor the labels are ignored.

struct CC{     double a_;     double b_;     CC(double a, double b) : a_{a}, b_{b}{} };  CC cc{.a_ = 1., .b_ = 2.}; assert(cc.a_ == 1. and cc.b_ == 2.); // ok CC cc{.b_ = 2., .a_ = 1.}; // compiles but labels don't matter only the order, confusing CC cc{.bla = 2., .bli = 1.}; // compiles but labels don't matter, confusing 

In other words the initializer syntax with a constructor make the label behave just as a comment!, which can be very confusing, but above all, it is very odd.

I discovered this accidentally, with gcc 8.1 -std=c++2a.

Is this the expected behavior?

Reference: https://en.cppreference.com/w/cpp/language/aggregate_initialization

 


Labels for designated initializers should not be ignored by compilers. All three of those examples with a constructor should be ill-formed.

You are likely getting this behavior due to a conflict between the C++20 designated initializer feature and GCC's C-style designated initializers which you are implicitly accessing due to GCC just giving them to you. If GCC were properly C++20-compiliant, once you gave the type a constructor, it would cease to be an aggregate and thus designated initializer usage would be ill-formed.

Basically, this is a driver bug caused by non-C++-standard behavior the compiler gives you by default. Odds are good that if you turn off this feature, you would get a proper compiler error for those cases.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: