After reading the article about safe typecasting, I followed the link to Stroustrup's
FAQ. I found this one really interesting:


Why doesn't C++ provide a "finally" construct?

Because C++ supports an alternative that is almost always better: The "resource
acquisition is initialization" technique (TC++PL3 section 14.4). The basic
idea is to represent a resource by a local object, so that the local object's
destructor will release the resource. That way, the programmer cannot forget
to release the resource. For example:
class File_handle {
FILE* p;
File_handle(const char* n, const char* a)
{ p = fopen(n,a); if (p==0) throw Open_error(errno); }
File_handle(FILE* pp)
{ p = pp; if (p==0) throw Open_error(errno); }

~File_handle() { fclose(p); }

operator FILE*() { return p; }

// ...

void f(const char* fn)
File_handle f(fn,"rw"); // open fn for reading and writing
// use file through f

In a system, we need a "resource handle" class for each resource. However,
we don't have to have an "finally" clause for each acquisition of a resource.
In realistic systems, there are far more resource acquisitions than kinds
of resources, so the "resource acquisition is initialization" technique leads
to less code than use of a "finally" construct.
Also, have a look at the examples of resource management in Appendix E of
The C++ Programming Language.


In a language such as C++, the idea was that it was best to enclose resources
inside classes so that "the programmer cannot forget to release the resource"!
Yet in .NET we MUST use a finally clause in EVERYTHING that uses a resource
class, and call Close() and/or Dispose() in that finally clause, if we want
to ensure that resources are cleaned up correctly.

This is (and has been) my one and only complaint about .NET -- I certainly
understand the benefit of garbage collection when dealing with systems of
many small objects whose resource usage is only memory. But for applications
that work with other types of resources frequently, .NET becomes cumbersome
and as error-prone to code in as straight C.

How hard would it be to add a facility for reference counting to ensure cleanup
of resources as soon as they go out of scope!