abhi4eternity
abhi4eternity

Reputation: 440

Creating an object of public ref class using new and gcnew

I have a class declared in MyRefClass.h

public ref class MyRefClass{
....
....
};

What is the difference between where/how the three objects are allocated and managed?

//  This is allocated in **C++/CLI**.
MyRefClass ^mrc = gcnew MyRefClass();
MyRefClass *mrc2 = new MyRefClass;

// If allocated in **C#**
MyRefClass mrc3 = new MyRefClass()

Pardon me if this is too silly a question. I am a total newbie in C# and C++/CLI.

Upvotes: -1

Views: 672

Answers (1)

xMRi
xMRi

Reputation: 15365

The second line with new is wrong and will not compile, even the syntax is wrong if it would be an unmanaged class. You must decalre a pointer to receive the result of the new operator.

In short:

Managed objects (ref class) must be allocated with gcnew. Managed objects live on the .NET managed heap and are freed by the garbage collector. Such classes/objects can be easily shared between all languages in the .NET world.

Unmanaged objects (class) must be allocated with new. They must be freed with delete. Such objects live on the normal process heap.

Upvotes: 1

Related Questions