Follow-up: Tale of the __dtor method and the delete operator

Wesner Moise wrote “So, how do we call the destructor from other managed languages, where destructor calls have to be explicit

If you can change the managed C++ code, then I would highly advise you to do so by implementing the IDisposable pattern. The Finalize method should not be the only code that releases unmanaged resources (e.g. network connections). See Finalization and The Dispose Pattern.


But I guess you can’t, can you?


In that case, you might want to hide that detail for other managed languages by wrapping the call to __dtor(). If you care about the Whidbey release of C++ in the future, you’re better of calling delete on the instance.


I guess you’ll get the idea with the sample code below.


Your C++ wrapper for the managed C++ Foo class:

public __gc class FooDestructor : public IDisposable



      static void Delete( Foo * p ) { delete p ; }


      FooDestructor( Foo * p ) : m_pFoo(p) {}


      void Dispose() { Delete( m_pFoo ) ; }



      Foo * m_pFoo ;

} ;


Note: I’m not taking into account multi-threading issues and calling methods on instance already disposed.


And here is some C# code that shows how to use it with the using keyword, and then explicitly with the static Delete method.


Foo f = new Foo() ;



   using ( new FooDestructor( f ) )


      int i = 0 ;

      Console.WriteLine( 1 / i ) ;





   Console.ReadLine() ;


Foo f1 = new Foo() ;

FooDestructor.Delete( f1 ) ;

Console.ReadLine() ;


Does it make sense?



Comments (0)

Skip to main content