在 c++ 中,c-casting 到 type 或 type 的引用有什么区别?
foo = (unsigned int) whatever;
// Is this the same as:
foo = (unsigned int&) whatever;
不,它甚至完全不一样。
(在某些情况下,演员表的确切性质取决于是什么whatever。我会假设类型与whatever无关unsigned int。)
对引用类型unsigned int &的 C 转换等价于reinterpret_cast对该类型执行 a
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;
将value转换为ftype unsigned int,这意味着i将接收 value 5。同时,如果在您的平台尺寸unsigned int和尺寸float相同,那么这个
unsigned int i = (unsigned int &) f;
实际上会将具有 value的floatobject的内部对象表示重新解释为 type 的对象。的结果值通常是不可预测的。通常它甚至不会接近(在流行的实现中,您将简单地收到 中原始值的 IEE754 表示)。f5unsigned inti5floati