27 ms·
FYI - designated initializers in C++20 require that the designators appear in the same order as the field declarations in the struct or class[1]. If the designa
by alexhutcheson 7y ago
FYI - designated initializers in C++20 require that the designators appear in the same order as the field declarations in the struct or class[1]. If the designators aren't in the same order as they appear in the struct declaration, the behavior of the designated initializer statement is undefined. Note that this is different from C - C99 supports a broader variety of designated initializers than C++20 - there's a table in the document I linked.
Because of this, the statement "Changing the order of the struct args won't introduce ordering bugs like with function signatures" is actually not true - I know from experience that clang will sometimes just silently leave the struct uninitialized, which could lead to nasty bugs. The behavior can also vary between optimized and debug builds, so it might not surface when you run your unit tests, etc.
I believe that once C++20 is standardized both compilers will probably introduce warnings or errors to let you know when you've unintentionally initialized fields out of order, but for right now the feature is a landmine and I wouldn't recommend using it.
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0329r0.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p032...
- CoolGuySteve 7y agog++ gives an error if you do things out of order. But what I meant is that this is still better than a regular function signature. ie: int f(int a, int b) changed to f(int b, int a) works but the arguments will be wrong if the call site doesn't change. f({ .a = 1, .b = 2}) will fail at the call site when the struct is changed to expect f({ .b = 2, .a = 1}) But yes, while ideally the order of declaration wouldn't matter, C++ is going the other way, being extremely strict about initialization order to avoid complex constructor errors. I wish POD types would be treated differently for those warnings/errors.
- alexhutcheson 7y agoMakes sense - I misunderstood what you meant by order. It’s good to know that g++ gives you an error if the designator are out of order - thanks for pointing that out.