c++20 std::reinterpret_cast、std::bit_cast、std::static_cast

std::reinterpret_cast 类型不相关 的转换,不安全 例如转为&,不支持,要求sizeof相同

cpp 复制代码
uint32_t n32 = 12345678;//0x00bc614e
uint32_t* ptr = reinterpret_cast<uint32_t*>(n32);//0x00bc614e
uint32_t& ref = reinterpret_cast<uint32_t&>(n32);//0x00bc614e 危险操作
uint32_t n32a = *reinterpret_cast<uint32_t*>(n32);//崩溃,非法内存访问
uint16_t n16 = reinterpret_cast<uint16_t>(n32);;//编译错误error C2440: "reinterpret_cast": 无法从"uint32_t"转换为"uint16_t"
float f = reinterpret_cast<float>(n);//error C2440: "reinterpret_cast": 无法从"uint32_t"转换为"float"
}

std::bit_cast 将源对象的位解释为目标对象位,不可转为&,要求sizeof相同无损的转换,用于可复制类型的二进制IO,例如将字节写入文件,再读回内存。

cpp 复制代码
bool b = is_trivially_copyable_v<int&>;//false
float f = 3.14f;//0x4048f5c3
uint32_t n32 = std::bit_cast<uint32_t>(f);//0x4048f5c3
uint32_t n32ref = std::bit_cast<uint32_t&>(f);//编译不通过error C2672: "std::bit_cast": 未找到匹配的重载函数//is_trivially_copyable_v<int&>;//false
uint16_t n16 = std::bit_cast<uint16_t>(f);//编译不通过error C2672: "std::bit_cast": 未找到匹配的重载函数//bool_constant<sizeof(_To) == sizeof(_From)>

//uint32_t无损转为float
//实现1
uint32_t Value = 0x12345678;
float Tr_Data = *((float*)(&Value));//0x12345678
//实现2
float f = std::bit_cast<float>(0x12345678);//0x12345678

std::static_cast随意转换 ,可能是有损的转换,级别较低,不出现编译错误,问题不容易被发现。

cpp 复制代码
float f = 33333333.14f;//0x4bfe502b
uint32_t i = static_cast<uint32_t>(f);//0x01fca056
uint32_t n32 = (uint32_t)f;//0x01fca056
uint16_t n16 = (uint16_t)f;//0x0000a056
//static_cast想怎么转都能转成功,可能是有损的转换

reinterpret_cast不能在constexpr中使用,std::bit_cast可以。reinterpret_cast是语言功能,std::bit_cast是库函数,库函数比语言功能容易支持。

相关推荐
charlie1145141915 天前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
charlie1145141917 天前
理解C++20的革命特性——协程引用之——利用协程做一个迷你的Echo Server
网络·学习·socket·c++20·协程·epoll·raii
charlie1145141917 天前
理解C++20的革命特性——协程支持2:编写简单的协程调度器
c++·学习·算法·设计模式·c++20·协程·调度器
charlie1145141918 天前
精读C++20设计模式——结构型设计模式:外观模式
c++·学习·设计模式·c++20·外观模式
渡我白衣8 天前
C++ :std::bind 还能用吗?它和 Lambda 有什么区别?
开发语言·c++·c++20
charlie1145141919 天前
理解C++20的革命特性——协程支持1
c++·学习·c++20·协程·语言特性·调度·现代c++
渡我白衣9 天前
C++20 协程:在 AI 推理引擎中的深度应用
大数据·人工智能·c++20
charlie1145141919 天前
精读 C++20 设计模式:行为型设计模式 — 访问者模式
c++·学习·设计模式·访问者模式·c++20
charlie11451419110 天前
精读C++20设计模式——行为型设计模式:命令模式
c++·学习·设计模式·程序设计·命令模式·c++20
charlie11451419111 天前
精读C++20设计模式——行为型设计模式:迭代器模式
c++·学习·设计模式·迭代器模式·c++20