C ++转换为void的目的是什么? [英] C++ What is the purpose of casting to void?
本文介绍了C ++转换为void的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
将未使用的返回值转换为void
一些源代码,并且在其中许多接口类中的虚拟函数被声明和默认实现如下:
I read some source code, and in it many virtual functions in the interface classes are declared and default-implemented as such:
virtual bool FunctionName(TypeName* pointer)
{
(void)pointer;
return true;
}
我可以问在默认情况下将指针转换为void的目的是什么
May I ask what is the purpose of casting the pointer to void in the default implementation?
推荐答案
多种用途取决于你所投入的内容
Multiple purposes depending on what you cast
- 标记您希望编译器表示完全是无操作的表达式是为了写入(例如禁止警告)
- 标记您的意图编译器和程序员,忽略某事的结果(例如,函数调用的结果)
- 在函数模板中,如果返回类型由模板参数类型
T
,并且在某些情况下返回可能与T
不同的某个函数调用的结果。在void
的情况下,显式转换为T
可以防止编译时错误:
int f(){return 0; } void g(){return(void)f(); }
- 禁止编译器选择逗号运算符重载(
(void)a,b
调用重载的逗号运算符函数)。
- Marking your intention to the compiler that an expression that is entirely a no-op is intended as written (for inhibiting warnings, for example)
- Marking your intention to to the compiler and programmer that the result of something is ignored (the result of a function call, for example)
- In a function template, if a return type is given by a template parameter type
T
, and you return the result of some function call that could be different fromT
in some situation. An explicit cast toT
could, in thevoid
case, prevent a compile time error:
int f() { return 0; } void g() { return (void)f(); }
- Inhibiting the compiler to choose a comma operator overload (
(void)a, b
will never invoke an overloaded comma operator function).
请注意,标准保证永远不会有 ()
(如果你把一个类对象转换为 void
(一些GCC版本忽略该规则)。
Note that the Standard guarantees that there will never be an operator void()
called if you cast a class object to void
(some GCC versions ignore that rule, though).
这篇关于C ++转换为void的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文