Winterdom

C++/CLI has two ways of dealing with objects supporting IDisposable. The first one is to explicitly call delete on the object as soon as you want to dispose of it, like this:


public ref class File
{
public:
   ~File()
   {
      // dispose unmanaged stream
   }
   // ...
};

int main()
{
   File^ file = gcnew File();
   try {
      //...
   } finally {
      delete file;
   }
}

Calling delete will force the compiler to emit a call to IDisposable::Dispose on the object. It's interesting to notice you can call delete on a handle to any managed object, whether it implements IDisposable or not, though. The compiler will generate the necessary code to test for an IDisposable implementation and call Dispose() if it is supported, or simply do nothing if it isn't. The use of the object is enclosed in a try {} finally {} block to ensure delete is called on any case.

The second way to deal with IDisposable objects is stack allocation of reference types. You could rewrite the above code like this:


int main()
{
   File file;
   //...
   // file goes out of scope
}

In this case, the compiler will simply ensure that Dispose() is called when the object goes out of scope, even in the case of an exception (it generates the necessary try{} block for you). It has a very nice syntax to it (it's simpler) and it is very consistent with the usual RAII (Resource Allocation is Initialization) idiom used in standard C++ programming.

.: tomasr | 2004-10-10 18:47:12 :.