为什么将未使用的返回值转换为

为什么将未使用的返回值转换为

本文介绍了为什么将未使用的返回值转换为 void?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int fn();

void whatever()
{
    (void) fn();
}

是否有任何理由将未使用的返回值转换为 void,或者我认为这完全是在浪费时间?

Is there any reason for casting an unused return value to void, or am I right in thinking it's a complete waste of time?

跟进:

嗯,这看起来很全面.我认为这比注释未使用的返回值要好,因为自记录代码比注释更好.就个人而言,我会关闭这些警告,因为这是不必要的噪音.

Well that seems pretty comprehensive. I suppose it's better than commenting an unused return value since self documenting code is better than comments. Personally, I'll turn these warnings off since it's unnecessary noise.

如果有虫子因此逃脱,我会吃我的话......

I'll eat my words if a bug escapes because of it...

推荐答案

David 的 answer 几乎涵盖了这样做的动机,明确向其他开发人员"表明您知道此函数返回但您明确忽略了它.

David's answer pretty much covers the motivation for this, to explicitly show other "developers" that you know this function returns but you're explicitly ignoring it.

这是一种确保始终处理必要的错误代码的方法.

This is a way to ensure that where necessary error codes are always handled.

我认为对于 C++ 来说,这可能是唯一我更喜欢使用 C 样式转换的地方,因为在这里使用完整的静态转换符号感觉有点过头了.最后,如果您正在审查编码标准或正在编写一个编码标准,那么明确声明对重载运算符的调用(不使用函数调用符号)也应免于这一点也是一个好主意:

I think for C++ this is probably the only place that I prefer to use C-style casts too, since using the full static cast notation just feels like overkill here. Finally, if you're reviewing a coding standard or writing one, then it's also a good idea to explicitly state that calls to overloaded operators (not using function call notation) should be exempt from this too:

class A {};
A operator+(A const &, A const &);

int main () {
  A a;
  a + a;                 // Not a problem
  (void)operator+(a,a);  // Using function call notation - so add the cast.

这篇关于为什么将未使用的返回值转换为 void?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 04:38