此代码是否有效? GCC 和 Clang 不同意

Is this code valid or not? GCC and Clang disagree

以下代码在 GCC 和 Clang 上给出了不同的结果。谁是对的?

union Foo {
    struct {
        int a;
        int b;
    };
};

struct Bar {
    Bar(void) : test{.a = 1, .b = 2} { }
    Foo test;
};

我在 GCC 中遇到了以下错误(并且它在 Clang 中编译得很好):

arcanis@/tmp # g++ -std=c++11 x.cpp 
x.cpp: In constructor ‘Bar::Bar()’:
x.cpp:9:36: error: too many initializers for ‘Foo’
     Bar(void) : test{.a = 1, .b = 2} { }
                                    ^

使用 GCC 4.9.1 和以下选项:

-Wall -Wextra -std=c++11 -pedantic 

这是你得到的:

prog.cc:7:5: warning: ISO C++ prohibits anonymous structs [-Wpedantic]
 };
 ^ 
prog.cc: In constructor 'Bar::Bar()':
prog.cc:11:21: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
Bar(void) : test{.a = 1, .b = 2} { }
                ^ 
prog.cc:11:28: warning: ISO C++ does not allow C99 designated initializers [-Wpedantic]
Bar(void) : test{.a = 1, .b = 2} { }
                       ^ 
prog.cc:11:36: error: too many initializers for 'Foo'
Bar(void) : test{.a = 1, .b = 2} { }
                               ^

使用具有相同选项的 Clang 3.5.0,您将获得几乎相同的结果:

prog.cc:4:5: warning: anonymous structs are a GNU extension [-Wgnu-anonymous-struct]
    struct {
   ^ 
prog.cc:11:22: warning: designated initializers are a C99 feature [-Wc99-extensions] 
   Bar(void) : test{.a = 1, .b = 2} { }
                    ^~~~~~ 
prog.cc:11:30: warning: designated initializers are a C99 feature [-Wc99-extensions] 
   Bar(void) : test{.a = 1, .b = 2} { } 
                            ^~~~~~

简而言之,这不是有效的 C++11 代码,警告消息中明确指出了两个原因。 Clang 恰好容忍它并且只发出警告,而不是错误。我不确定在这种情况下是否值得辩论“谁是对的”。