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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
CWG 2360 | C++17 | 无法将 [[maybe_unused]] 应用于结构化绑定 | 允许 |
[编辑] 参考文献
- C++23 标准 (ISO/IEC 14882:2024)
- 9.12.8 Maybe unused 属性 [dcl.attr.unused]
- C++20 标准 (ISO/IEC 14882:2020)
- 9.12.7 Maybe unused 属性 [dcl.attr.unused]
- C++17 标准 (ISO/IEC 14882:2017)
- 10.6.6 Maybe unused 属性 [dcl.attr.unused]
[编辑] 参见
C 文档 关于 maybe_unused
|