.net gcnew 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/202459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is gcnew?
提问by Owen
I stumbled across this code and am too proud to go and ask the author what it means.
我偶然发现了这段代码,我很自豪不能去问作者这意味着什么。
Hashtable^ tempHash = gcnew Hashtable(iterators_);
IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();
What is gcnewand how important is it to use that instead of simply new? (I'm also stumped by the caret; I asked about that over here.)
回答by Steven A. Lowe
回答by Joel Coehoorn
gcnewis an operator, just like the newoperator, except you don't need to deleteanything created with it. It's garbage collected. You use gcnewfor creating .Net managed types, and newfor creating unmanaged types.
gcnew是一个操作符,就像new操作符一样,只是你不需要delete用它创建任何东西。它的摹arbage Çollected。您可以使用gcnew用于创建.NET托管类型,以及new用于创建非托管类型。
回答by user2796283
The caret '^' acts simarly to the '*' in C/C++ when declaring a type;
声明类型时,插入符号“^”的作用类似于 C/C++ 中的“*”;
// 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.
我在描述托管对象时使用术语“指针”,因为托管对象可以与“nullptr”进行比较,就像 C/C++ 中的指针一样。C/C++ 中的引用无法与 'nullptr' 进行比较,因为它是现有对象的地址。
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.
托管对象使用自动引用计数,这意味着当它们的引用计数为零时它们会被自动销毁,尽管如果两个或多个无法访问的对象相互引用,您仍然会出现内存泄漏。请注意,自动引用计数不是免费的,因此请明智地使用它。

