1.关于GCroots和gcnew.
常说的GC(Garbage Collector) roots,特指的是垃圾收集器(Garbage Collector)的对象,GC会收集那些不是GC roots且没有被GC roots引用的对象。C /CLI中使用gcnew关键字表示在托管堆上分配内存,并且为了和以前的指针区分,用^来替换* ,就语义上来说他们的区别大致如下:
1. gcnew返回的是个句柄(Handle),而new返回的是实际的内存地址.
2. gcnew创建的对象由虚拟机托管,而new创建的对象必须自己来管理和释放.
几个代码实例:
using namespace System; ref class Foo { public: Foo() { System::Console::WriteLine("Foo::Foo"); } ~Foo() { System::Console::WriteLine("Foo::~Foo"); } public: int m_iValue; }; int _tmain() { int* pInt = new int; int^ rInt = gcnew int; Foo^ rFoo = gcnew Foo; delete rFoo; delete rInt; delete pInt; }
// mcpp_gcroot.cpp // compile with: /clr #include <vcclr.h> using namespace System; class CppClass { public: gcroot<String^> str; // can use str as if it were String^ CppClass() {} }; int main() { CppClass c; c.str = gcnew String("hello"); Console::WriteLine( c.str ); // no cast required }
// mcpp_gcroot_2.cpp // compile with: /clr // compile with: /clr #include <vcclr.h> using namespace System; struct CppClass { gcroot<String ^> * str; CppClass() : str(new gcroot<String ^>) {} ~CppClass() { delete str; } }; int main() { CppClass c; *c.str = gcnew String("hello"); Console::WriteLine( *c.str ); }
// mcpp_gcroot_3.cpp // compile with: /clr #include < vcclr.h > using namespace System; public value struct V { String^ str; }; class Native { public: gcroot< V^ > v_handle; }; int main() { Native native; V v; native.v_handle = v; native.v_handle->str = "Hello"; Console::WriteLine("String in V: {0}", native.v_handle->str); }