Namespaces
Variants

C++ attribute: maybe_unused (since C++17)

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
Attributes
(C++23)
(C++11) (until C++26)
(C++14)
(C++20)
maybe_unused
(C++17)
(C++17)
(C++11)
(C++20)

抑制未使用实体的警告。

目录

语法

[ [ maybe_unused ] ]

说明

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

(since C++26)

对于声明为 [ [ maybe_unused ] ] 的实体,如果该实体或其结构化绑定未被使用,编译器将抑制关于未使用实体的警告。

对于声明为 [ [ maybe_unused ] ] 的标签,若未被使用,编译器将抑制针对未使用标签发出的警告。

(since C++26)

示例

#include <cassert>
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2)
{
    [[maybe_unused]] lbl: // 标签“lbl”未被使用,不产生警告
    [[maybe_unused]] bool b = not false and not true;
    assert(b); // 在发布模式下,assert被编译移除,变量“b”未被使用
               // 因其声明为[[maybe_unused]]而不产生警告
} // 参数“thing1”和“thing2”未被使用,不产生警告
int main() {}

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
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 可能未使用属性 [dcl.attr.unused]
  • C++17 标准 (ISO/IEC 14882:2017):
  • 10.6.6 可能未使用属性 [dcl.attr.unused]

参见

C 文档 关于 maybe_unused