[C#]C++/CLI中^的含义
阅读原文时间:2023年07月08日阅读:2
// here normal pointer
P* ptr = new P; // usual pointer allocated on heap
P& nat = *ptr; // object on heap bind to native object

//.. here CLI managed
MO^ mngd = gcnew MO; // allocate on CLI heap
MO% rr = *mngd; // object on CLI heap reference to gc-lvalue

解释:在C++/CLI中,^指向托管的对象,对象的内存回收由CLR垃圾回收器自动管理,当然我们也可以用*来创建手动管理内存对象。

参考几个Stackoverflow上的答案:

It means that this is a reference to a managed object vs. a regular C++ pointer. Objects behind such references are managed by the runtime and can be relocated in the memory. They are also garbage-collected automatically.

When you allocated managed memory, that memory can be moved around by the garbage collector. The ^ operator is a pointer for managed memory, that continues to point to the correct place even if the garbage collector moves the object it points to.