What is gcnew?

.NetC++ Cli

.Net Problem Overview


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 gcnew and how important is it to use that instead of simply new? (I'm also stumped by the caret; I asked about that over here.)

.Net Solutions


Solution 1 - .Net

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

Solution 2 - .Net

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

Solution 3 - .Net

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOwenView Question on Stackoverflow
Solution 1 - .NetSteven A. LoweView Answer on Stackoverflow
Solution 2 - .NetJoel CoehoornView Answer on Stackoverflow
Solution 3 - .Netuser2796283View Answer on Stackoverflow