c-casting以针对c-casting键入类型的引用

时间:2013-01-17 17:26:37

标签: c++ casting enums

在c ++中,c-casting与类型或类型引用的区别是什么?

foo = (unsigned int) whatever;  

// Is this the same as: 
foo = (unsigned int&) whatever;  

1 个答案:

答案 0 :(得分:5)

不,它甚至不是一样的。

(在某些情况下,演员的确切性质取决于whatever是什么。我将假设whatever的类型与unsigned int无关。)

C-casting到引用类型unsigned int &相当于对该类型执行reinterpret_cast

foo = reinterpret_cast<unsigned int &>(whatever);  

根据定义等同于

foo = *reinterpret_cast<unsigned int *>(&whatever);  
在这种情况下,

whatever必须是左值。

换句话说,转换为引用只是类型双关语的另一种方法。您很简单重新解释 whatever占用的内存作为unsigned int对象。通常情况下,行为未定义。例如,如果sizeof whatever小于unsigned int的大小,则重新解释还会涉及一些甚至不属于whatever的“狂野”内存。

同时,非参考C-cast只是一个值转换,而不是内存重新解释。对于unsigned int的算术转换,它等同于static_cast(但如果whatever是指针,则它等同于reinterpret_cast)。它会读取whatever,并根据语言转换规则将其转换为unsigned int类型(如果存在转换)。

例如,这个

float f = 5;
unsigned int i = (unsigned int) f;

会将f转换为unsigned int类型,这意味着i将获得值5。同时,如果您的平台尺寸unsigned intfloat尺寸相同,那么

unsigned int i = (unsigned int &) f;
实际上,

会将值float的{​​{1}}对象f的内部对象表示重新解释为5类型的对象。 unsigned int的结果值通常是不可预测的。通常它甚至不会接近i(在流行的实现中,您只需在5中收到原始float值的IEE754表示。