-1

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.

abhi4eternity
  • 448
  • 3
  • 8
  • 19
  • gcnew and the ^ hat are just reminders that you are no longer in Kansas anymore. Managed objects behave differently at runtime and that is something you always need to be aware of. It is *not* arbitrary, you can't use new and * on a ref class. Equipping the C++ language with an aggressive garbage collector did force them for you to be explicit about what you had in mind, Very Bad Things happen when you can't make your mind up yet. Be sure to follow a decent tutorial or introductory book. – Hans Passant Jun 29 '18 at 22:19

1 Answers1

1

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.

xMRi
  • 14,982
  • 3
  • 26
  • 59
  • Thanks for your reply. I should have clearly stated that mrc2 was being allocated in C#. I updated the question and hope it makes more sense now. – abhi4eternity Jun 28 '18 at 16:40
  • And still the second allocation with new in C++/CLI will not work! – xMRi Jun 28 '18 at 20:47