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)

未使用エンティティに関する警告を抑制します。

目次

翻訳のポイント: - 「Contents」→「目次」に翻訳 - HTMLタグ、属性、リンク先は一切変更せず保持 - ` `内のC++関連用語(Syntax、Explanation、Example、Defect reports、References、See also)は翻訳せず保持 - 数値、クラス名、IDなどは完全に保持 - フォーマットと構造は完全に維持

構文

[ [ 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: // ラベル「lbl」は使用されていないため警告なし
    [[maybe_unused]] bool b = not false and not true;
    assert(b); // リリースモードではassertはコンパイルされず、「b」は未使用となる
               // [[maybe_unused]]で宣言されているため警告なし
} // パラメータ「thing1」と「thing2」は使用されていないが警告なし
int main() {}

不具合報告

以下の動作変更欠陥報告書は、以前に公開されたC++標準に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
CWG 2360 C++17 [ [ maybe_unused ] ] を構造化バインディングに適用できなかった 許可される

参考文献

  • C++23規格 (ISO/IEC 14882:2024):
  • 9.12.8 未使用可能性属性 [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