C++ 屬性:maybe_unused (C++17 起)
來自 cppreference.com
抑制對未使用的實體的警告。
目錄 |
[編輯] 語法
[[maybe_unused]]
|
|||||||||
[編輯] 解釋
此屬性可以出現在以下實體的宣告中
- 類:struct [[maybe_unused]] S;
- typedef,包括透過類型別名宣告宣告的:[[maybe_unused]] typedef S* PS;,using PS [[maybe_unused]] = S*;
- 變數,包括靜態資料成員:[[maybe_unused]] int x;
- 非靜態資料成員:union U { [[maybe_unused]] int n; };,
- 函式:[[maybe_unused]] void f();
- 列舉:enum [[maybe_unused]] E {};
- 列舉器:enum { A [[maybe_unused]], B [[maybe_unused]] = 42 };
- 結構化繫結:[[maybe_unused]] auto [a, b] = std::make_pair(42, 0.23);
|
(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
|