C 風格 (Type)expr 混合了多種語意,編譯器無法精準檢查,易掩蓋錯誤。C++ 提供四個具備明確語意、可編譯期檢查的轉型運算子。
static_cast(expr)
void* 轉具體指標、移除 const/volatile(需配合 const_cast)。const/volatile/__unaligned 屬性。dynamic_cast(expr)
void* 轉型。nullptr;引用轉型失敗拋出 std::bad_cast。static_cast 慢。class Base { virtual void f() {} };
class Derived : public Base { int extra; };
Base* pb = new Base;
Derived* pd1 = static_cast(pb); // 編譯通過,執行危險
Derived* pd2 = dynamic_cast(pb); // 回傳 nullptr,安全
Base* pb2 = new Derived;
Derived* pd3 = dynamic_cast(pb2); // 成功
// 交叉轉型
class A { virtual void f() {} };
class B : public A {};
class C : public A {};
B* b = new B;
C* c1 = static_cast(b); // 編譯錯誤
C* c2 = dynamic_cast(b); // 回傳 nullptr
reinterpret_cast(expr)
int n = 9;
double d1 = static_cast(n); // 正確轉換:9.0(補齊位元)
double d2 = reinterpret_cast(n); // 錯誤位元解讀:垃圾值
const_cast(expr)
const/volatile 資格。const(如字串常數區),透過結果修改導致未定義行為。const int ci = 10;
int* p = const_cast(&ci);
*p = 20; // UB!ci 可能在唯讀區
// 正當用途:呼叫非 const 介面的舊 API
void legacy_api(int* p);
const int* cptr = &ci;
legacy_api(const_cast(cptr)); // 確保 API 不會修改
| 場景 | 推薦運算子 |
|---|---|
| 基類→衍生類(確知安全) | static_cast |
| 基類→衍生類(需執行期驗證) | dynamic_cast |
| 基本型別互轉、void* 轉具體指標 | static_cast |
| 指標↔整數、無關類別強制轉換 | reinterpret_cast |
| 移除 const/volatile | const_cast |
四大轉型運算子各司其職:static_cast 為主力,dynamic_cast 守護多態安全,reinterpret_cast 處理底層位元操作,const_cast 解決舊介面相容。**嚴禁使用 C 風格轉型**,讓編譯器成為你的安全網。