为什么将未使用的返回值强制转换为 void?

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

问题描述

int fn();

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

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?

Follow up:

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'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.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What are access specifiers? Should I inherit with private, protected or public?(什么是访问说明符?我应该以私有、受保护还是公共继承?)
What does extern inline do?(外部内联做什么?)
Why can I use auto on a private type?(为什么我可以在私有类型上使用 auto ?)
How to implement big int in C++(如何在 C++ 中实现大 int)
C++ template typedef(C++ 模板类型定义)
Why does the use of #39;new#39; cause memory leaks?(为什么使用“新会导致内存泄漏?)