简体   繁体   English

允许转换为void(不是指针),为什么?

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

Why can I cast this vector to a void (not even a pointer)? 为什么我可以将此向量转换为void(甚至不是指针)?

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

How come this is allowed? 怎么允许这个?

Casting to void simply discards the result of the expression. 转换为void只会丢弃表达式的结果。 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); 在C ++中,您应该编写static_cast<void>(expr); rather than (void)expr; 而不是(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). 任何表达式都可以显式转换为cv void类型,在这种情况下,它将成为废弃值表达式(第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. [注意:但是,如果值在临时对象(12.2)中,则该对象的析构函数在正常时间之前不会执行,并且为了执行析构函数而保留对象的值。 —end note ] - 尾注]

ISO/IEC 14882:2011 5.2.9 par. ISO / IEC 14882:2011 5.2.9 par。 6 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM