复制位模式:float to uint32_t

Copy bit pattern: float to uint32_t

float 值的位模式复制到 uint32_t 中,反之亦然(不转换它们),我们可以使用 std::copy 或 [= 逐字节复制位16=]。另一种方法是使用 reinterpret_cast 如下 (?):

float f = 0.5f;
uint32_t i = *reinterpret_cast<uint32_t*>(&f);

uint32_t i;
reinterpret_cast<float&>(i) = 10;

然而,有一个 claim 表示上面使用了两个 reinterpret_cast,调用未定义的行为。真的吗?怎么样?

是的,这是未定义的行为,因为它违反了严格的别名规则:

[basic.lval]/10: If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined — the dynamic type of the object,

— a cv-qualified version of the dynamic type of the object,

— a type similar (as defined in 4.4) to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

— an aggregate or union type that includes one of the aforementioned types among its elements or non- static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

— a type that is a (possibly cv-qualifded) base class type of the dynamic type of the object,

— a char or unsigned char type.

由于 uint32_t 是上面的 none,当试图访问类型为 float 的对象时,行为未定义。