Search code examples
visual-studio-2010.net-4.0c++-cli

Do I need to call delete on IDisposable object in C++/CLI


I had been under the impression that in a C++/CLI method if a class I was using implements IDisposable, the dispose is auto-magically called when the object goes out of scope. Recently I came across some code that looks like this:

void SomeClass::SomeMethod()
{
    DisposableObject^ myObject = nullptr;
    try
    {
         // Some code that creates a DisposableObject and assigns to myObject
    }
    finally
    {
        if (myObject != nullptr)
        {
            // this is instead of IDisposable.Dispose
            delete myObject;
        }
    }
}

My question is sort of two fold really. First, do I need to explicitly call delete on the object. Secondly, in pure C++ it is safe to call delete on a null object, does that behavior change in C++/CLI, just wondering because it seems like I don't really need the nullptr check around the delete call if the behavior is the same in C++/CLI (I understand behavior the same is a relative term since the delete on a managed object is doing different things than on an unmanaged object).


Solution

    1. You never strictly need to dispose anything in .NET (unless the class is implemented incorrectly, e.g. lacks a finalizer when one is warranted), but you absolutely should whenever possible. Using stack semantics obviates the need to call delete directly when lazy initialization is not needed:

      void SomeClass::SomeMethod() {
          DisposableObject myObject;
          // ...
          // Some code that uses myObject
      } // myObject is disposed automatically upon going out of scope
      

      Using msclr::auto_handle<> in combination with stack semantics obviates the need for a try..finally when lazy initialization is needed:

      void SomeClass::SomeMethod() {
          msclr::auto_handle<DisposableObject> myObject;
          // ...
          // Some code that creates a DisposableObject and assigns to myObject
          // ...
          // Some code that uses myObject
      } // myObject is disposed automatically upon going out of scope
      
    2. Calling delete on a value of nullptr is completely safe, defined behavior, just as in C++ – no need for the if.