问题
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