C++ What is the purpose of casting to void? [duplicate]

蹲街弑〆低调 提交于 2019-11-26 08:30:32

问题


Possible Duplicate:
casting unused return values to 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;
}

May I ask what is the purpose of casting the pointer to void in the default implementation?


回答1:


Multiple purposes depending on what you cast

  • 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 from T in some situation. An explicit cast to T could, in the void 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).

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




回答2:


In this case it's just to avoid compiler's warning about unused parameter.



来源:https://stackoverflow.com/questions/4178695/c-what-is-the-purpose-of-casting-to-void

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!