Why cast unused return values to void?(为什么将未使用的返回值转换为 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么将未使用的返回值转换为 void?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
