davidA
davidA

Reputation: 13664

How to get away with using designated initializers in C++17? Or, why is it seemingly safe to use them, if it's really not?

C++20 introduced support for designated initializers.

In g++ with -std=c++17, one can use designated initializers and as long as you don't leave any out, it will compile without any errors or warnings:

struct Foo {
    int a;
    float b;
};

Foo f {
    .a = 7,
    .b = 42.1f,
};

Yet if I enable -Wpedantic (and -Werror) the C++17 compiler will spit out:

error: C++ designated initializers only available with '-std=c++20' or '-std=gnu++20' [-Werror=pedantic]

But there does not seem to be a way to disable or suppress this error without disabling -Wpedantic too, which is far too coarse in my case.

I find this very confounding because there's no warning emitted when using this feature with C++17 - code using it will compile and run, seemingly, with un-undefined behaviour, yet from everything I've found online it's not supposed to be used with C++17.

So why isn't there a warning or error when using this unsupported feature with C++17 without -Wpedantic? Surely it's not pedantic to warn the user of a non-supported language feature if it's technically UB? And if it's not UB, then it works, right?

Lastly, without recompiling g++, how can I trick the compiler into accepting -Wpedantic without generating such warnings if I choose to use designated initializers in my C++17 code?

Upvotes: 7

Views: 3901

Answers (1)

davidA
davidA

Reputation: 13664

I'll answer it myself based on the helpful comment from Peter:

"[My] understanding is backward. C++17 does not support designated initialisers at all but g++ (and other compilers) included experimental/provisional support for features before their eventual acceptance in the standardisation process. Due to historical lobbying by developers (from a time when their PAY was, say, tied to metrics like "compile without warnings") modern compilers do NOT diagnose non-standard features by default, and using -pedantic DIRECTS the compiler to diagnose them. Your options are (1) compile as C++20 (2) don't use -pedantic or (3) don't use designated initialisers."

There, a solid answer from Peter that explains my incorrect assumptions and provides suggestions for a course of action.

Upvotes: 7

Related Questions