static_cast
用于编译时相关的类型转换,dynamic_cast
用于运行时多态类的安全向下转换,const_cast
用于移除或添加const
/volatile
属性,而reinterpret_cast
则用于低级别的位模式重新解释。
static_cast
- 静态类型转换
用途
示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| double d = 3.14; int i = static_cast<int>(d);
class Base {}; class Derived : public Base {}; Derived derived; Base* base = static_cast<Base*>(&derived);
Base* base_ptr = new Derived(); Derived* derived_ptr = static_cast<Derived*>(base_ptr);
|
特点
- 编译时完成
- 不进行运行时检查
- 相对安全(在合理范围内)
dynamic_cast
- 动态类型转换
用途
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Base { virtual ~Base() {} }; class Derived : public Base {};
Base* base_ptr = new Derived();
Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr); if (derived_ptr) { } else { }
try { Derived& derived_ref = dynamic_cast<Derived&>(*base_ptr); } catch (std::bad_cast& e) { }
|
特点
- 运行时检查
- 需要 RTTI(运行时类型信息)
- 只适用于多态类型(有虚函数)
- 安全但性能开销较大
const_cast
- 常量性转换
用途
示例
1 2 3 4 5 6 7 8 9 10 11 12 13
| const int ci = 10; int* modifiable = const_cast<int*>(&ci); *modifiable = 20;
void legacy_func(char* str); const char* hello = "hello"; legacy_func(const_cast<char*>(hello));
int x = 42; const int* cx = const_cast<const int*>(&x);
|
特点
- 只改变常量性,不改变类型
- 移除 const 后修改原对象是未定义行为
- 主要用于接口兼容
reinterpret_cast
- 重新解释转换
用途
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| int x = 0x12345678; char* bytes = reinterpret_cast<char*>(&x);
for (std::size_t index = 0; index < 4; ++index) { cout << hex << int(bytes[0 + index]) << " "; }
uintptr_t addr = reinterpret_cast<uintptr_t>(&x);
int* ptr = reinterpret_cast<int*>(addr);
struct A { int a; }; struct B { double b; }; A a{42}; B* bp = reinterpret_cast<B*>(&a);
|
特点
- 最低层的转换
- 高度平台相关
- 几乎不做任何检查
- 最后的选择
对比总结
特性 |
static_cast |
dynamic_cast |
const_cast |
reinterpret_cast |
安全性 |
中等 |
高 |
低 |
极低 |
检查时机 |
编译时 |
运行时 |
编译时 |
无检查 |
性能开销 |
无 |
有 |
无 |
无 |
主要用途 |
相关类型转换 |
多态类型安全转换 |
常量性修改 |
底层二进制转换 |
失败行为 |
可能未定义行为 |
返回 nullptr(指针)或抛出异常(引用) |
未定义行为(如果错误使用) |
几乎总是成功但危险 |
使用指南
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Base { virtual ~Base() {} }; class Derived : public Base {};
Base* base = new Derived();
Derived* derived1 = dynamic_cast<Derived*>(base); if (derived1) { }
Derived* derived2 = reinterpret_cast<Derived*>(base);
|
核心原则:优先使用安全的转换,只在必要时使用危险的转换,并充分了解其风险。