【问题标题】:Can attributes be applied to constructor parameters?属性可以应用于构造函数参数吗?
【发布时间】:2019-05-21 04:37:27
【问题描述】:

Clang 8.0.0 和 GCC 9.1.0 在这是否是有效代码方面似乎存在分歧。

struct Foo {
  Foo([[maybe_unused]] int x) {}
};
int main() {}

Clang 不会产生警告(即使使用 -Wall -Wextra -Wpedantic),但 GCC 会产生此错误:

test.cpp:2:7: error: expected unqualified-id before '[' token
    2 |   Foo([[maybe_unused]] int x) {}
      |       ^
test.cpp:2:7: error: expected ')' before '[' token
    2 |   Foo([[maybe_unused]] int x) {}
      |      ~^
      |       )

那么哪个编译器有bug?

【问题讨论】:

    标签: c++ language-lawyer compiler-bug


    【解决方案1】:

    是的,它们可以应用。标准允许这样做。

    10.6.6 可能未使用的属性[dcl.attr.unused]
    ...
    2 该属性可应用于类、typedef-name、变量、非静态数据成员、函数、枚举或枚举器的声明。

    所以 Clang 在这里是正确的,这是一个 GCC 错误。 已经为此提交了一份错误报告,标题为:maybe_unused attribute triggers syntax error when used on first argument to a constructor

    【讨论】:

    • 令人毛骨悚然的错误报告还写了Foo([[maybe_unused]] int x)。很遗憾,报告打开了这么久都没有修复。
    • 将近两年后它甚至没有分配给任何人。
    【解决方案2】:

    您的代码有效

    [[maybe_unused]] 属性可以应用于结构、枚举、联合的声明, typedef、变量(包括成员变量)、函数或枚举器。实现是 鼓励在未使用此类实体或使用该实体时不发出诊断信息,尽管 被标记为[[maybe_unused]]

    但是 gcc maybe_unused attribute triggers syntax error when used on first argument to a constructor 中已经有一个错误报告。 gcc 可能无法正确解析。

    【讨论】:

      【解决方案3】:

      这可能是您的 GCC 编译行中的一个问题。 运行以下行时,我收到类似的错误:

      gcc *.cpp -o run_me
      

      但是,使用以下行时没有问题:

      gcc -std=c++17 *.cpp -o run_me -Wall -Wextra -Wpedantic
      

      使用标准 c++11 运行将给出警告“使用 'maybe_unused' 属性是 C++17 扩展”。编译此代码时请务必使用 c++17。

      【讨论】:

        猜你喜欢
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-26
        • 1970-01-01
        相关资源
        最近更新 更多