gpt4 book ai didi

c++ - 如何故意丢弃 [[nodiscard]] 返回值?

转载 作者:IT老高 更新时间:2023-10-28 22:17:43 28 4
gpt4 key购买 nike

说我有

[[nodiscard]] int foo ()
{
return 0;
}

int main ()
{
foo ();
}

然后

error: ignoring return value of ‘int foo()’, declared with attribute nodiscard [-Werror=unused-result]

但是如果

int x = foo ();

然后

error: unused variable ‘x’ [-Werror=unused-variable]

有没有一种简洁的方式告诉编译器“我想丢弃这个 [[nodiscard]] 值”?

最佳答案

Cast it to void :

[[nodiscard]] int foo ()
{
return 0;
}

int main ()
{
static_cast<void>(foo());
}

这基本上告诉编译器“是的,我知道我正在丢弃它,是的,我很确定。

关于c++ - 如何故意丢弃 [[nodiscard]] 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581744/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com