托管 C++(Managed C++)語法晦澀、雙底線充斥,微軟於 2003 年推動 ECMA 標準化,催生 C++/CLI,隨 Visual Studio 2005 發布。C++/CLI 保留 C++ 精髓,提供優雅的 CLI 整合體驗。
__gc、__property 等)閱讀負擔重。* 同時表示原生指標與 __gc 指標,行為迥異。^(句柄)取代 __gc*,gcnew 取代 new,消除雙底線。| 概念 | 舊語法 | C++/CLI |
|---|---|---|
| 參考型別宣告 | __gc class R | ref class R |
| 值型別宣告 | __value struct V | value struct V |
| 介面宣告 | __interface I | interface class I |
| 控制代碼 | R* r = new R(); | R^ r = gcnew R(); |
| 裝箱 | 隱含 | 隱含(Object^ o = 44;) |
| 拆箱 | 隱含/不安全 | 顯式 reinterpret_cast<int^>(o) |
// 參考型別
ref class RefClass { ... };
ref struct RefStruct { ... };
// 值型別
value class ValClass { ... };
value struct ValStruct { ... };
// 介面
interface class IType { ... };
// 列舉
enum class Color { Red, Green, Blue };
// 原生型別(不變)
class Native { ... };
struct Native { ... };
裝箱在 CLR 堆建立物件副本,拆箱需 reinterpret_cast 且嚴格檢查型別:
int z = 44;
Object^ o = z; // 隱含裝箱
int y = *reinterpret_cast<int^>(o); // 顯式拆箱
Object^ o1 = 44;
Object^ o2 = 33.567f;
Console::WriteLine(o1->GetType()); // System.Int32
Console::WriteLine(o2->GetType()); // System.Single
// *reinterpret_cast<int^>(o2) → InvalidCastException