13

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;
TownCube
  • 1,280
  • 1
  • 13
  • 32

1 Answers1

17

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.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • So other then marking the object for more immediate GC there isn't really any good reason to use delete in the above example? – TownCube Aug 17 '11 at 08:48
  • 3
    @Cube : No, fulfulling your end of the `IDisposable` contract is an excellent reason to **always** use `delete` whenever you're done with an object. Or better yet, use stack semantics for simulated RAII so you never have to use `delete`, and `Dispose` will automatically be called as soon as objects go out of scope. – ildjarn Aug 17 '11 at 15:34