首页 > 解决方案 > 属性可以应用于构造函数参数吗?

问题描述

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) {}
      |      ~^
      |       )

那么哪个编译器有错误?

标签: c++language-lawyercompiler-bug

解决方案


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

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

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


推荐阅读