允许强制转换为void(非指针),为什么? [英] Casting to void (not pointer) is allowed, why?

查看:68
本文介绍了允许强制转换为void(非指针),为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要将此向量强制转换为空值(甚至没有指针)?

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

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

这怎么允许?

推荐答案

将void强制转换为void只会丢弃表达式的结果.有时,您会看到人们使用它来避免未使用的变量"或忽略的返回值"警告.

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.

在C ++中,您可能应该编写 static_cast< void>(expr); ,而不是(void)expr;

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.

标准说:

任何表达式都可以显式转换为cv void类型,其中在这种情况下,它成为一个废弃值表达式(第5条).[ 笔记:但是,如果该值位于临时对象(12.2)中,则析构函数直到平时才执行该对象,并且保留对象是为了执行析构函数.—尾注]

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参数6

这篇关于允许强制转换为void(非指针),为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆