这段代码有效吗? GCC和Clang不同意

时间:2015-02-22 11:29:47

标签: c++11 gcc clang initializer-list

以下代码给出了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} { }
                                    ^

1 个答案:

答案 0 :(得分:4)

使用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恰好容忍它并且只发出警告而不是错误。我不确定在这种情况下是否值得辩论'谁是对的'。