.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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:20:04  来源:igfitidea点击:

What is gcnew?

.netc++-cli

提问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.)

gcnew使用它而不是简单地使用它是什么以及有多重要new?(我也被插入符号难住了;我在这里过这个问题。)

回答by Steven A. Lowe

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

gcnew用于 .NET 引用对象;使用 gcnew 创建的对象会自动进行垃圾回收;将 gcnew 与 CLR 类型一起使用很重要

回答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.

托管对象使用自动引用计数,这意味着当它们的引用计数为零时它们会被自动销毁,尽管如果两个或多个无法访问的对象相互引用,您仍然会出现内存泄漏。请注意,自动引用计数不是免费的,因此请明智地使用它。