名稱空間
變體
操作

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

來自 cppreference.com
< 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