命名空间
变体
操作

C 属性: nodiscard (自 C23 起)

来自 cppreference.cn
< c‎ | language‎ | attributes

如果从一个丢弃值表达式(而非强制转换为void)调用声明为 nodiscard 的函数,或者调用返回声明为 nodiscard 的结构体/联合体/枚举的函数,则编译器被鼓励发出警告。

目录

[编辑] 语法

[[ nodiscard ]]
[[ __nodiscard__ ]]
(1)
[[ nodiscard ( string-literal ) ]]
[[ __nodiscard__ ( string-literal ) ]]
(2)
string-literal - 可用于解释为什么不应丢弃结果的理由的文本

[编辑] 解释

出现在函数声明、枚举声明或结构体/联合体声明中。

如果从一个丢弃值表达式(而非强制转换为void),

  • 调用了声明为 nodiscard 的函数,或者
  • 调用了返回声明为 nodiscard 的结构体/联合体/枚举的函数,

则编译器被鼓励发出警告。

如果指定了 string-literal,通常会包含在警告中。

[编辑] 示例

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