C++ 屬性:nodiscard (自 C++17 起)
來自 cppreference.com
如果一個被宣告為 `nodiscard` 的函式,或者一個返回被宣告為 `nodiscard` 的列舉或類的函式以值傳遞方式被從丟棄值表示式中呼叫(除了轉換為 void 的情況),編譯器應發出警告。
目錄 |
[編輯] 語法
[[nodiscard]]
|
(1) | (C++17 起) | |||||||
[[nodiscard( string-literal )]] |
(2) | (C++20 起) | |||||||
字串字面量 | - | 一個未求值的字串字面量,可用於解釋不應丟棄結果的原因。 |
[編輯] 解釋
出現在函式宣告、列舉宣告或類宣告中。
如果,從一個丟棄值表示式中(除了轉換為 void 的情況):
- 呼叫了被宣告為 `nodiscard` 的函式,或
- 呼叫了返回被宣告為 `nodiscard` 的列舉或類的函式(按值傳遞),或
- 透過顯式型別轉換或static_cast呼叫了被宣告為 `nodiscard` 的建構函式,或
- 透過顯式型別轉換或static_cast初始化了被宣告為 `nodiscard` 的列舉或類型別物件,
編譯器應發出警告。
如果指定了 string-literal,通常會包含在警告中。 |
(C++20 起) |
[編輯] 示例
執行此程式碼
struct [[nodiscard]] error_info { /*...*/ }; error_info enable_missile_safety_mode() { /*...*/ return {}; } void launch_missiles() { /*...*/ } void test_missiles() { enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value launch_missiles(); } error_info& foo() { static error_info e; /*...*/ return e; } void f1() { foo(); } // nodiscard type is not returned by value, no warning // nodiscard( string-literal ) (since C++20): [[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; } int main() { strategic_value(4, 2); // compiler may warn on discarding a nodiscard value auto z = strategic_value(0, 0); // OK: return value is not discarded return z; }
可能的輸出
game.cpp:5:4: warning: ignoring return value of function declared with ⮠ 'nodiscard' attribute game.cpp:17:5: warning: ignoring return value of function declared with ⮠ 'nodiscard' attribute: PURE FUN
標準庫以下標準函式使用 `nodiscard` 屬性宣告:
|
(直到 C++26) |
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P1771R1 | C++17 | 建構函式上的 [[nodiscard]] 無效 |
如果構造的物件被丟棄,可能會導致警告 |
[編輯] 參考資料
- C++23 標準 (ISO/IEC 14882:2024)
- 9.12.9 Nodiscard 屬性 [dcl.attr.nodiscard]
- C++20 標準 (ISO/IEC 14882:2020)
- 9.12.8 Nodiscard 屬性 [dcl.attr.nodiscard]
- C++17 標準 (ISO/IEC 14882:2017)
- 10.6.7 Nodiscard 屬性 [dcl.attr.nodiscard]
[編輯] 另請參閱
(C++11) |
使用 tie 解包 tuple 時跳過元素的佔位符(常量) |
C 文件 for nodiscard
|