命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 语言‎ | 属性
 
 
C++ 语言
 
 
属性
(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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
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