c++ - 复制位模式: float 到uint32_t

标签 c++ undefined-behavior primitive-types reinterpret-cast

float值的位模式复制到uint32_t中,反之亦然(不强制转换),我们可以使用std::copymemcpy逐位复制位。另一种方法是使用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类型的对象时,float并非以上所述,因此行为未定义。

关于c++ - 复制位模式: float 到uint32_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744365/

相关文章:

c++ - 运行时错误-UndefinedBehaviourSanitizer

methods - 访问原始 Rust 类型的方法

java - 空 Java 字符串的大小

c++ - C++ 中的模板参数存储在哪里?

c - 当 p 指向一个字符时,strcmp(p, "\n") 是未定义的行为吗?

c++ - AES - 如何在 C++ 中编写逆子字节?

c - 段错误(核心转储)- strlcpy 函数 C

java - 添加非原始类型数据作为节点和关系中的属性值

c++ - 定义聚合

c++ - 如何使用 main() 构建支持多个目标的 makefile