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是库函数,库函数比语言功能容易支持。

相关推荐
抓饼先生16 小时前
C++ 20 视图view笔记
linux·开发语言·c++·笔记·c++20
郝学胜-神的一滴2 天前
深入浅出 C++20:新特性与实践
开发语言·c++·程序人生·算法·c++20
_不会dp不改名_20 天前
C++ 20: Concepts 与Requires
开发语言·c++20
arbboter1 个月前
【C++20】新特性探秘:提升现代C++开发效率的利器
c++·c++20·新特性·span·结构化绑定·初始化变量·模板参数推导
猿饵块1 个月前
c++20--std::format
c++20
mrbone112 个月前
C++-关于协程的一些思考
开发语言·数据库·c++·c++20·协程·异步·coroutines
xiaolang_8616_wjl2 个月前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
十年编程老舅2 个月前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
xiaolang_8616_wjl2 个月前
c++游戏_小恐龙(开源)
开发语言·数据结构·c++·算法·游戏·开源·c++20
a东方青3 个月前
[蓝桥杯C++ 2024 国 B ] 立定跳远(二分)
c++·算法·蓝桥杯·c++20