Something all C++ programmers should know when using managed C++

| 0 Comments
Beware! The rules for when a destructor is called for a managed C++ class in Visual C++ are different than for "normal" C++ class.

Jochen Kalmbach recently posed a simple question about a managed C++ class; "Will the destructor be called in a managed class if the constructor has thrown an exception?". The answer and the comments are illuminating and, to be honest, somewhat annoying.

In summary, yes, the destructor is called even if the constructor doesn't complete, see here for more details. This is different to normal C++ where the destructor is only called if the constructor completes, see here for more details.

I'm sure that someone, somewhere, thinks that this change is there for a good reason but to me it, and the corresponding complexity of the explanations of how managed C++ destructors and finalizers work over at MSDN is indicative of the designers not worrying enough about ease of use for the programmer... But then it's easy for me to say that when I haven't been involved in the detail of the design and it's always easier to poke fun at the solution than it is to solve the problem. ;)

Leave a comment