C++ 属性:maybe_unused (C++17 起)
来自 cppreference.cn
抑制对未使用的实体的警告。
目录 |
[编辑] 语法
[[maybe_unused]]
|
|||||||||
[编辑] 解释
此属性可以出现在以下实体的声明中
- 类:struct [[maybe_unused]] S;
- typedef,包括通过类型别名声明声明的:[[maybe_unused]] typedef S* PS;,using PS [[maybe_unused]] = S*;
- 变量,包括静态数据成员:[[maybe_unused]] int x;
- 非静态数据成员:union U { [[maybe_unused]] int n; };,
- 函数:[[maybe_unused]] void f();
- 枚举:enum [[maybe_unused]] E {};
- 枚举器:enum { A [[maybe_unused]], B [[maybe_unused]] = 42 };
- 结构化绑定:[[maybe_unused]] auto [a, b] = std::make_pair(42, 0.23);
|
(C++26 起) |
对于声明为 [[maybe_unused]] 的实体,如果这些实体或它们的结构化绑定未使用,编译器发出的有关未使用实体的警告将被抑制。
对于声明为 [[maybe_unused]] 的标签,如果它们未使用,编译器发出的有关未使用标签的警告将被抑制。 |
(C++26 起) |
[编辑] 示例
运行此代码
#include <cassert> [[maybe_unused]] void f([[maybe_unused]] bool thing1, [[maybe_unused]] bool thing2) { [[maybe_unused]] lbl: // the label “lbl” is not used, no warning [[maybe_unused]] bool b = not false and not true; assert(b); // in release mode, assert is compiled out, and “b” is unused // no warning because it is declared [[maybe_unused]] } // parameters “thing1” and “thing2” are not used, no warning int main() {}
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
CWG 2360 | C++17 | 不能将 [[maybe_unused]] 应用于结构化绑定 | 允许 |
[编辑] 参考
- C++23 标准 (ISO/IEC 14882:2024)
- 9.12.8 Maybe unused attribute [dcl.attr.unused]
- C++20 标准 (ISO/IEC 14882:2020)
- 9.12.7 Maybe unused attribute [dcl.attr.unused]
- C++17 标准 (ISO/IEC 14882:2017)
- 10.6.6 Maybe unused attribute [dcl.attr.unused]
[编辑] 另请参阅
C 文档 中的 maybe_unused
|