Visual C++ 團隊在 VS 2005 重新設計 CLR 支援,稱為「C++/CLI」,提供更自然的語法撰寫與使用 CLR 型別。本文探討新語法並與 C#、Managed C++ 比較,輔以圖表對照原生 C++。
原生 C++ 允許自由選擇配置位置,語法清晰區分:
// 堆疊
std::wstring stackObject;
// CRT 堆
std::wstring* heapObject = new std::wstring;
C# 配置位置由型別決定,語法無差異:
System.DateTime stackObject = new System.DateTime(2003, 1, 18); // 實值型別 -> 堆疊
System.IO.MemoryStream heapObject = new System.IO.MemoryStream(); // 參考型別 -> 托管堆
// 實值型別 - 正常
DateTime stackObject(2003, 1, 18);
// 參考型別 - 怪異
IO::MemoryStream __gc* heapObject = __gc new IO::MemoryStream;
// 或推斷簡寫 (但非真指標)
IO::MemoryStream* heapObject = new IO::MemoryStream;
問題:* 語義重載,GC 移動物件導致指標值變更,無法從程式碼判斷配置位置。
// 實值型別 - 無變化
DateTime stackObject(2003, 1, 18);
// 參考型別 - 清楚明確
IO::MemoryStream^ heapObject = gcnew IO::MemoryStream;
^ 宣告 CLR 參考型別控制代碼,GC 移動物件時自動更新。gcnew 明確指示托管堆配置;new 僅用於 CRT 堆 (除非自訂)。原生 C++ 指標與 CLR 物件參考本質不同。C++/CLI 引入控制代碼徹底分離兩者,消除語義重載與歧義,提供自然、型別安全、高效能的 .NET 程式設計體驗。