C attribute: nodiscard (since C23)
From cppreference.net
<
c
|
language
|
attributes
如果声明为
nodiscard
的函数,或返回被声明为
nodiscard
的结构体/联合体/枚举类型按值返回的函数,在
被舍弃值表达式
中被调用(除强制转换为
void
的情况外),编译器将建议发出警告。
目录 |
语法
[[
nodiscard
]]
[[
__nodiscard__
]]
|
(1) | ||||||||
[[
nodiscard
(
字符串字面量
)
]]
[[
__nodiscard__
(
字符串字面量
)
]]
|
(2) | ||||||||
| string-literal | - | 可用于解释为何不应舍弃该结果的说明文本 |
说明
出现在函数声明、枚举声明或结构体/联合体声明中。
如果,从 弃值表达式 中(除了强制转换为 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(); // 编译器可能对丢弃 nodiscard 值发出警告 launch_missiles(); } struct error_info* foo() { static struct error_info e; /*...*/ return &e; } void f1() { foo(); // nodiscard 类型本身未被返回,无警告 } // nodiscard( 字符串字面量 ): [[nodiscard("PURE FUN")]] int strategic_value(int x, int y) { return x ^ y; } int main() { strategic_value(4,2); // 编译器可能对丢弃 nodiscard 值发出警告 int z = strategic_value(0,0); // 正常:返回值未被丢弃 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
|