What is gcnew?

左心房为你撑大大i 提交于 2019-11-28 06:09:17
Steven A. Lowe

gcnew is for .NET reference objects; objects created with gcnew are automatically garbage-collected; it is important to use gcnew with CLR types

Joel Coehoorn

gcnew is an operator, just like the new operator, except that you don't have to delete anything created with it. It's garbage collected. You use gcnew for creating .Net managed types, and new for creating unmanaged types.

The caret '^' acts simarly to the '*' in C/C++ when declaring a type;

// pointer to new std::string object -> memory is not garbage-collected
std::string* strPtr = new std::string;

// pointer to System::String object -> memory is garbage-collected
System::String^ manStr = gcnew System::String;

I use the term 'pointer' when describing the managed object as a managed object can be compared to 'nullptr' just like a pointer in C/C++. A reference in C/C++ can not be compared to 'nullptr' as it is the address of an existing object.

Managed objects use automatic-reference-counting meaning that they are destroyed automatically when they have a reference count of zero although if two or more unreachable objects refer to eachother, you will still have a memory leak. Be warned that automatic reference counting is not free performance wise so use it wisely.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!