Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should delete be called on a gcnew allocated object?

I was reading the following MSKB example and they perform a delete on a managed object.

I was under the impression you should never delete a garbaged collected object rather you must leave that to garbage collector.

What have I missed?

Method 4

 //#include <msclr/marshal.h>
 //using namespace msclr::interop;
 marshal_context ^ context = gcnew marshal_context();
 const char* str4 = context->marshal_as<const char*>(str);
 puts(str4);
 delete context;
like image 407
TownCube Avatar asked Aug 17 '11 02:08

TownCube


People also ask

Does Gcnew need delete?

No, never. This is . NET managed memory allocation, the object are destructed and memory reclaimed by the Garbage Collector (GC).

What does Gcnew mean in C++?

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.


1 Answers

delete in C++/CLI merely calls the Dispose method on a managed object, if it implements the System::IDisposable interface – if it doesn't, it's effectively a noop. In fact, if you try to call the Dispose method on a managed object yourself, you'll get a compiler error – delete is the enforced idiom for disposing an object.

To be clear, it has nothing to do with memory management, noting of course that most finalizable objects will get GCed sooner if they're disposed.

like image 156
ildjarn Avatar answered Oct 07 '22 20:10

ildjarn