名稱空間
變體
操作

C 屬性: nodiscard (C23 起)

來自 cppreference.com
< c‎ | 語言‎ | 屬性

如果一個被宣告為 nodiscard 的函式,或者一個返回被宣告為 nodiscard 的結構體/聯合體/列舉的函式,在除了強制轉換為 void 之外的丟棄值表示式中被呼叫,編譯器會鼓勵發出警告。

目錄

[編輯] 語法

[[ nodiscard ]]
[[ __nodiscard__ ]]
(1)
[[ nodiscard ( 字串字面量 ) ]]
[[ __nodiscard__ ( 字串字面量 ) ]]
(2)
字串字面量 - 可以用來解釋為什麼結果不應該被丟棄的文字

[編輯] 解釋

出現在函式宣告、列舉宣告或結構體/聯合體宣告中。

如果,在除了強制轉換為 void 之外的丟棄值表示式中,

  • 呼叫了被宣告為 nodiscard 的函式,或者
  • 呼叫了返回被宣告為 nodiscard 的結構體/聯合體/列舉的函式,

編譯器會鼓勵發出警告。

如果指定了字串字面量,它通常會包含在警告中。

[編輯] 示例

struct [[nodiscard]] error_info { int status; /*...*/ };
struct error_info enable_missile_safety_mode() { /*...*/ return (struct error_info){0}; }
void launch_missiles() { /*...*/ }
void test_missiles() {
   enable_missile_safety_mode(); // compiler may warn on discarding a nodiscard value
   launch_missiles();
}
struct error_info* foo() { static struct error_info e; /*...*/ return &e; }
void f1() {
    foo(); // nodiscard type itself is not returned, no warning
}
// nodiscard( string-literal ):
[[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
    int 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

[編輯] 另請參閱

C++ 文件,瞭解 nodiscard