【问题标题】:GCC attribute warning with trailing return type when return type is a class当返回类型是类时,带有尾随返回类型的 GCC 属性警告
【发布时间】:2014-12-10 19:07:51
【问题描述】:

当返回类型是类时,GCC 4.9.1 似乎不喜欢带有属性的尾随返回类型的函数声明。

考虑以下简单的测试用例:

struct bar
{
    int a;
    bar (int a) : a(a) {}
};

auto foo() -> bar __attribute__((unused));
auto foo() -> bar { return bar(5); }

int main()
{
    return 0;
}

GCC 打印一个关于属性的奇怪警告:

argh.cpp:2:41: warning: ignoring attributes applied to class type ‘bar’ outside of definition [-Wattributes]
 auto foo() -> bar __attribute__((unused)) {return bar(5);}

将声明与定义合并不会使警告静音,并且仅当返回类型是类类型时才会发生这种情况,它适用于int。到底是怎么回事?为什么 GCC 不喜欢这个特定的函数声明?

【问题讨论】:

    标签: c++ c++11 gcc


    【解决方案1】:

    似乎是 GCC 使用的属性解析器中的一个错误。 GCC 手册警告属性语法的潜在问题:

    6.31 属性语法

    由于属性的语法不合理,某些形式 此处描述的可能并非在所有情况下都能成功解析。

    C++ 中属性的语义存在一些问题。 [...] 例如,属性没有修饰,尽管它们可能会影响代码生成,因此当属性类型与模板或重载一起使用时可能会出现问题。

    在尾随返回类型之后的属性解析警告也会有所帮助。

    属性说明符列表可能会出现在声明符之前 [...]

    您应该尝试将属性放在原型之前:

     __attribute__((unused)) 
    auto foo() -> bar ;
    auto foo() -> bar { return bar(5); }
    

    它应该没有任何警告。

    属性说明符列表可能出现在逗号之前,= 或分号终止标识符的声明,而不是 函数定义。此类属性说明符适用于声明的 对象或函数。

    我猜想在函数声明之后定位函数属性是可以的,除非有尾随返回类型。

    【讨论】:

      【解决方案2】:

      Clang(像往常一样)在这种情况下会给出更好的警告:

      example.cpp:7:34: warning: 'unused' attribute ignored when parsing type
            [-Wignored-attributes]
      auto foo() -> bar __attribute__((unused));
                                       ^~~~~~
      1 warning generated.
      

      就像 GCC 告诉你的那样,这个属性在你使用它的上下文中是没有意义的。它在概念上与执行以下操作相同:

      const int f(void) { return 5 };
      

      那里的const 没有任何意思

      【讨论】:

        【解决方案3】:

        GCC manual 表示目前不支持该语法。

        未来可能允许出现一个属性说明符列表 在函数定义中的声明符之后(在任何旧式 参数声明或函数体)。

        N3337 描述了 [dcl.fct.def] 中函数定义的语法:

        函数定义:

                attribute-specifier-seqoptdecl-specifier-seqoptdeclarator virt-specifier -seqopt函数体

        ...

        2 function-definition 中的 declarator 应具有以下形式

        D1 (parameter-declaration-clause) cv-qualifier-seqopt

                 ref-qualifieroptexception-specificationoptattribute-specifier-seqopttrailing-return-typeopt

        如您所见,trailing-return-typedeclarator 的一部分,它出现在 function-body 之前。尝试将您的代码更改为:

        auto __attribute__((unused)) foo() -> bar;
        

        【讨论】:

          猜你喜欢
          • 2019-10-22
          • 2010-11-11
          • 2015-09-10
          • 1970-01-01
          • 1970-01-01
          • 2018-03-11
          • 2018-05-12
          • 1970-01-01
          • 2022-06-12
          相关资源
          最近更新 更多