Search code examples
c++-cli

What is the difference between "= gcnew MyClass()" and "= %MyClass()"?


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.


Solution

  • 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 '^'