1

What is the difference between

MyClass ^myClass = gcnew MyClass();

and

MyClass ^myClass = %MyClass();

if any?

Both seem to work, but not sure what happens behind the scenes.

Zsolt Bán
  • 13
  • 2
  • 2
    Not at all the same, the 2nd statement is a broken way to use "stack semantics". Normally written as `MyClass myClass;`, intentionally omitting the ^ hat. The big, big difference is that the object is automatically disposed at the end of the scope block. If you're familiar with C++ then it is the equivalent of RAII. If you're familiar with C# then it the is the equivalent of the `using` statement. Start googling, this is important, query for "c++/cli stack semantics". – Hans Passant Aug 17 '19 at 22:22
  • @HansPassant thanks for the more expert insight. I tried to reason about the problem from the c++-cli documentation online, but I am no expert. Your response is more useful and accurate. – Matthew E. Miller Aug 18 '19 at 00:12
  • @HansPassant Thank you. On [this page](https://learn.microsoft.com/en-us/cpp/dotnet/cpp-stack-semantics-for-reference-types?view=vs-2019) Microsoft says that the compiler does internally create the instance on the garbage collected heap (using gcnew), but does not create copy constructors. So "MyClass myClass = MyClass();" does not work unless I implement a copy constructor, however "MyClass ^myClass = %MyClass();" does work... So I guess my related question is... why? – Zsolt Bán Aug 18 '19 at 08:04
  • To clarify further the above: I thought "MyClass ^myClass = %MyClass();" can be also written as "MyClass mc = MyClass(); MyClass ^myClass = %mc;" but it does not seem to be the case. – Zsolt Bán Aug 18 '19 at 08:16

1 Answers1

0

Revision:

Stack Semantics


Previous:
So, in both cases a newly created object's address is assigned to a pointer. For this reason, the two statements appear to work the same.

The Difference:
Using gcnew allocates memory of a managed type (reference), that has garbage collection.

Using %MyClass() is analogous to using &MyClass(), which does not have garbage collection.

gcnew:
Memory for a managed type (reference or value type) is allocated by gcnew, and deallocated by using garbage collection.

%MyClass():
Like standard C++, this object will not be garbage collected. Operator overloading works analogously to standard C++. Every * becomes a ^, every & becomes an %.

Meaning of '^':
The handle declarator (^, pronounced "hat"), modifies the type specifier to mean that the declared object should be automatically deleted when the system determines that the object is no longer accessible.

Relevant Links:
Meaning of '%', Search "Operator Overloading"
Meaning of gcnew
Meaning of '^'

Matthew E. Miller
  • 557
  • 1
  • 5
  • 13