Dispose my $%!

I’ve just come across you particularly annyoing feature in the new Version of the C++ Managed Extensions for .NET.

For garbage-collected languages, it is recommended that you follow the “Dispose” pattern in order to free non-memory resources. That’s a well established pattern, if you want to know more about it you can read here or here. There are a few rules on how to implement this pattern. Microsoft also added an interface for disposable objects, that allows for some syntactic sugar.

However in the “new” version of the Managed Extensions for C++, they came up with a different way to implement the dispose pattern. This mimics the way destructors work in plain C++.

They also came up with the brilliant idea that it should not be allowed to call the Dispose() method directly:

From a Microsoft blog:

A bit of discussion about Dispose brought up an interesting point – in C++, now, we’ve disabled the ability to call the Dispose function directly. Instead, you call it thusly:

ref class MyClass{
~MyClass(){} //overrides IDisposable::Dispose()

int main(){
MyClass^ mc = gcnew MyClass();
//do stuff
mc->Dispose(); //error!
mc->~MyClass(); //legal, calls Dispose()
delete mc; //also legal, also calls Dispose()

Now, whoever came up with that should be kicked in the butt. Quite hard.


Comments are closed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: