下面的代码为我提供了关于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只是碰巧容忍了它,只发出警告,而不是错误。我不确定在这种情况下是否值得争论"谁是对的"。