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?
答案 0 :(得分:4)
您的代码有效
[[maybe_unused]]
属性可以应用于struct,enum,union, typedef,变量(包括成员变量),函数或枚举数。实现是 鼓励在此类实体未使用或使用该实体时不发出诊断信息,尽管 被标记为[[maybe_unused]]
。
但是gcc
maybe_unused attribute triggers syntax error when used on first argument to a constructor中已经有关于此的错误报告。 gcc
可能无法正确解析。
答案 1 :(得分:4)
是的,可以应用它们。该标准允许这样做。
10.6.6也许未使用的属性[dcl.attr.unused]
...
2该属性可以应用于类,类型定义名称,变量,非静态数据成员,函数,枚举或枚举器的声明。
所以Clang在这里是正确的,这是一个GCC错误。 已为此提交了一个错误报告,标题为:maybe_unused attribute triggers syntax error when used on first argument to a constructor
答案 2 :(得分:0)
这可能是您的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。