reinterpret_cast 和 static_cast 的区别
安全性:
static_cast
是一个安全的类型转换,它只能转换具有继承关系或密切相关的类型,并且在编译时进行类型检查。
reinterpret_cast
是一个不安全的类型转换,它可以将任何类型的指针转换为任何其他类型的指针,而无需考虑类型安全性。
用途:
static_cast
用于转换具有继承关系或密切相关的类型,例如基类和派生类、整数类型和浮点类等。
reinterpret_cast
用于转换不相关的类型,例如指针类型和整数类型、结构体和联合体等。
使用场景
static_cast
- 从基类转换为派生类
- 从派生类转换为基类
- 从整数类型转换为浮点类型
- 从浮点类型转换为整数类型
- 从枚举类型转换为整数类型
reinterpret_cast
- 将指针类型转换为整数类型
- 将整数类型转换为指针类型
- 将结构体转换为联合体
- 将联合体转换为结构体
- 将函数指针转换为 void* 类型
- 将 void* 类型转换为函数指针
示例
static_cast
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Base { public : virtual void print() { std::cout << "Base" << std::endl; } }; class Derived : public Base { public : void print() override { std::cout << "Derived" << std::endl; } }; int main() { Base* base = new Derived(); Derived* derived = static_cast <Derived*>(base); // 安全的类型转换 derived->print(); // 输出:Derived return 0; } |
reinterpret_cast
1 2 3 4 | int * ptr = new int (10); void * voidPtr = reinterpret_cast < void *>(ptr); // 不安全的类型转换 int * newPtr = reinterpret_cast < int *>(voidPtr); // 不安全的类型转换 std::cout << *newPtr << std::endl; // 输出:10 |
需要注意的是,在使用 reinterpret_cast
时需要格外小心,因为它可能会导致未定义的行为或程序崩溃,如果转换的类型不兼容!
本文来自博客园,作者:{Justin_Hu},转载请注明原文链接:{https://www.cnblogs.com/gchenghu/}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)