命名空间
变体
操作

C++ 属性: maybe_unused (自 C++17 起)

来自 cppreference.cn
< cpp‎ | language‎ | 属性
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
范围 for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (在 C++11 中已弃用*)
noexcept 说明符 (C++11)
异常
命名空间
类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储期说明符
初始化
 
 
属性
(C++23)
(C++11)(直到 C++26)
(C++14)
(C++20)
maybe_unused
(C++17)
(C++17)
(C++11)
(C++20)
 

抑制关于未使用实体的警告。

目录

[编辑] 语法

[[maybe_unused]]

[编辑] 解释

此属性可以出现在以下实体的声明中

(自 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