Casting to void (not pointer) is allowed, why?

倖福魔咒の 提交于 2021-02-18 20:15:11

问题


Why can I cast this vector to a void (not even a pointer)?

int main()
{
   std::vector<int> a;
   (void)a;
}

How come this is allowed?


回答1:


Casting to void simply discards the result of the expression. Sometimes, you'll see people using this to avoid "unused variable" or "ignored return value" warnings.

In C++, you should probably write static_cast<void>(expr); rather than (void)expr;

This has the same effect of discarding the value, while making it clear what kind of conversion is being performed.

The standard says:

Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5). [ Note: however, if the value is in a temporary object (12.2), the destructor for that object is not executed until the usual time, and the value of the object is preserved for the purpose of executing the destructor. —end note ]

ISO/IEC 14882:2011 5.2.9 par. 6



来源:https://stackoverflow.com/questions/32828288/casting-to-void-not-pointer-is-allowed-why

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