本文介绍了如何有意丢弃[[nodiscard]]返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

说我有

[[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]] 值的一种干净方法?

Is there a clean way of telling the compiler "I want to discard this [[nodiscard]] value"?

推荐答案

讨论了通过强制转换为无效来使诊断静音的理由。它说强制转换为空是鼓励(如果不是非规范性的)使它静音的方法,该方法遵循现有实现对 __ attribute __((warn_unused_result))的作用:

The WG14 nodiscard proposal discusses the rationale for allowing the diagnostic to be silenced by casting to void. It says casting to void is the encouraged (if non-normative) way to silence it which follows what the existing implementation do with __attribute__((warn_unused_result)):

此属性的语义很大程度上取决于a的概念。用途,
的定义由实施人员自行决定。但是,WG21指定的非规范性指南中的
鼓励
实现在可能评估的舍弃值表达式中使用nodiscard函数
调用时发出警告诊断。
,除非它是明确转换为空的
。这意味着不鼓励
实现执行数据流分析(就像
初始化但未使用的局部变量诊断一样)。
...

The semantics of this attribute rely heavily on the notion of a use, the definition of which is left to implementation discretion. However, the non-normative guidance specified by WG21 is to encourage implementations to emit a warning diagnostic when a nodiscard function call is used in a potentially-evalulated discarded-value expression unless it is an explicit cast to void. This means that an implementation is not encouraged to perform dataflow analysis (like an initialized-but- unused local variable diagnostic would require). ...

C ++方式为 static_cast< void>

请参阅C ++标准草案[[:

See the draft C++ standard [[dcl.attr.nodiscard]p2:

这是一条注释,因此不是规范性的,但基本上这是现有实现对 __ attribute __((warn_unused_result))。另外,请注意,对 nodiscard 的诊断也是非规范的,因此,对违反 nodiscard 的诊断不是错误的形式,而是实现质量,就像通过强制转换来抑制一样

This is a note, so non-normative but basically this is what existing implementations do with __attribute__((warn_unused_result)). Also, note a diagnostic for nodiscard is also also non-normative, so a diagnostic for violating nodiscard is not ill-formed but a quality of implementation just like suppressing via a cast to void is.

参见:

这篇关于如何有意丢弃[[nodiscard]]返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:17