60

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

Community
  • 1
  • 1
Owen
  • 6,853
  • 8
  • 36
  • 50

3 Answers3

76

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

Chris Jester-Young
  • 206,112
  • 44
  • 370
  • 418
Steven A. Lowe
  • 58,325
  • 18
  • 127
  • 199
  • @[Chris Jester-Young]: Thanks Chris, that's good to know how to fix the MS links – Steven A. Lowe Oct 14 '08 at 19:53
  • 2
    Out of curiosity, how important is it to use `gcnew` with CLR types? Is it okay to statically declare a CLR type (ie use `System::String` instead of `System::String^`)? Will it correctly deallocate at the end of its lifetime/scope? – jliv902 Dec 01 '14 at 19:05
  • @jliv902: I doubt it - but I've been out of that sphere for a while! – Steven A. Lowe Dec 01 '14 at 23:08
48

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.

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
5

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.

user2796283
  • 243
  • 4
  • 8