Negative
Walter Bright
newshound at digitalmars.com
Mon Feb 27 22:58:43 PST 2006
"Andrew Fedoniouk" <news at terrainformatica.com> wrote in message
news:dtvl91$2dds$1 at digitaldaemon.com...
>
> This is real life example:
>
> Logger log = getLogger();
> try {
> File outf = getOutputFile(); // state managed outside
> File inf = getInputFile(); // state managed outside
> File tmpf = createTempFile();
> // lots of code
> } catch (Object e) {
> log.logFailure("...");
> throw e;
> } finally {
> delete tmpf;
> }
> log.close();
I don't see how it could be real life, since tmpf is not in scope in the
finally statement, so it won't compile. Furthermore, even if tmpf was in
scope, if getOutputFile() throws, then tmpf wouldn't have even been created
when the finally statement attempts to delete it. The log.close() also does
not reliably happen, as the throw e; statement would cause it to be skipped.
These kinds of issues are what on_scope_xxx are for. Let's rewrite it:
Logger log = getLogger();
on_scope_exit log.close();
on_scope_failure log.logFailure("...");
File outf = getOutputFile();
File inf = getInputFile();
File tmpf = createTempFile();
on_scope_exit delete tmpf;
...lots of code...
We don't have any more resource leaks.
More information about the Digitalmars-d
mailing list