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

相关推荐
小葡萄202511 小时前
黑马程序员c++2024版笔记 第一章 变量和基本类型
笔记·c++20
xiaolang_8616_wjl13 天前
c++_2011 NOIP 普及组 (1)
开发语言·数据结构·c++·算法·c++20
C咖咖15 天前
C++20 小语法
c++20
郭涤生23 天前
Concepts (C++20)
c++20
chendilincd24 天前
C++ 的史诗级进化:从C++98到C++20
java·c++·c++20
oioihoii1 个月前
C++20 统一容器擦除:std::erase 和 std::erase_if
c++20
郭涤生1 个月前
The whole book test_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
郭涤生1 个月前
Chapter 6: Concurrency in C++20_《C++20Get the details》_notes
开发语言·c++·笔记·c++20
__lost1 个月前
C++20的协程简介
c++20·协程
BanyeBirth1 个月前
C++2025年3月等级考试试题(部分)
c++20