在c ++中,c-casting与类型或类型引用的区别是什么?
foo = (unsigned int) whatever;
// Is this the same as:
foo = (unsigned int&) whatever;
答案 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 int
和float
尺寸相同,那么
unsigned int i = (unsigned int &) f;
实际上,会将值float
的{{1}}对象f
的内部对象表示重新解释为5
类型的对象。 unsigned int
的结果值通常是不可预测的。通常它甚至不会接近i
(在流行的实现中,您只需在5
中收到原始float
值的IEE754表示。