Jun 01, 2006

C++ and finally

Almost two months ago, Danny Kalev wrote a piece regarding adding finally to C++. Unlike Danny, however, I think this is a great addition to C++.

Danny has a good point that part of the reason that finally exists in garbage collected languages is that they lack a destruction mechanism that allows for cleaning up. For example, a common use of finally in Java is with files, sockets, and other such resources to ensure that the resource is guaranteed to be released (since the finalizer is not guaranteed to be ran). In C#, this could be done via the using keyword and hopefully in a future release on Java, a similar mechanism will exist that would allow the same behaviour.

But I think that there is a certain amount of value to adding such a feature to the language. For example, if you wanted to have a code segment display a log message at the end of a method, you would need to do something like:

For a general purpose tracing class, this would be, by far, the best approach. But for a specific operation that is done for one specific method, I think that the code above is not as readable as the same code written using a finally, even in the case where the statements in the finally explicitly call a function.

Said another way, the for keyword is equally redundant, since the 1998 C++ ISO Standard states in section 6.5.3 that the statement for ( for-init-statement ; condition ; expression ) statement is equivalent to:

But while the latter is equivalent to the former, there is a certain readability value that comes with the for statement that it is a welcomed keyword.

I feel that the addition of the finally keyword would have the same benefits. It is easily implemented in terms of existing infrastructure quite similar to the for example above is. It has adds increased readability, particularly for cases where the creation of a class would consume many more lines than a line or two in a finally block. Lastly, I think that there is a huge benefit to people using C++ that are accustomed to using other languages; the familiarity with this feature would permit such developers to concentrate on other, more important C++ features instead of trying to figure out how to get around the perceived lack of this feature. I think these benefits outweigh the cons of adding a new keyword, and I welcome the change.

Filed In