Re: C# vs. C++ (was Re: UNICODE conversion)
"David Wilkinson" <no-reply@effisols.com> wrote in message
news:uR6zOIThIHA.4396@TK2MSFTNGP04.phx.gbl...
Yes, that's it exactly. If you put the objects on the stack, then the
destructors get called regardless of whether exceptions are thrown.
Automatically. No "using", no "finally", no anything.
I just do not understand why this most elegant of C++ paradigms was
omitted from C#. Surely, the designers knew that there are resources other
than memory?
Ah, good guess! ;) Thanks to you and David L. for clarifying this. Still,
I don't believe it is exactly the same for the cleanup to occur in the
destructor/finalizer and in a 'finally' clause.
The 'finally' clause will execute after the exception is caught and handled
(in the same method that threw the exception). But cleanup code in the
destructor is only executed when the object is destroyed, which could be
some time later, if the exception was not fatal to the instance of the
object.
So if MyObject::foo() opens a file and throws and exception, if it has a
'finally' it can close the file before returning. But if you rely on
MyObject::~MyObject() to close the file, the file may stay open for a long
time after the exception was thrown. This is not good if the file needs to
be closed prior to other methods of MyObject are called, as they can be if
the object stays alive after the exception.
Thanks,
David