【问题标题】:Is this code valid or not? GCC and Clang disagree此代码是否有效? GCC 和 Clang 不同意
【发布时间】:2015-04-23 19:16:52
【问题描述】:

以下代码在 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} { }
                                    ^

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多