Negative

Walter Bright newshound at digitalmars.com
Mon Feb 27 23:11:28 PST 2006


"Andrew Fedoniouk" <news at terrainformatica.com> wrote in message 
news:du0hhf$a0u$1 at digitaldaemon.com...
> Why you think that your example is aesthetically
> better (technically they are the same) than this?
>
> Transaction abc()
> {
>    Foo f;   Bar b;  Def d;
>    try
>   {
>       f = dofoo();
>       b = dobar();
>       d = dodef();
>       return Transaction(f, b, d);
>   }
>   finally {
>      delete f; delete b; delete d;
>   }
> }

Technically, they are not the same. The above version *always* deletes f, b 
and d, but it's not supposed to if the function succeeds. Only if dofoo(), 
dobar(), or dodef() throws are f, b and d supposed to be deleted.

This is the whole problem with try-finally. It works great with trivial 
problems, and all the tutorials and example code unsurprisingly only show 
trivial problems. Try scaling it up for things like multi-step transactions, 
and it gets very complicated very fast, and it gets very hard to get right.

Here's the on_scope version:

Transaction abc()
{
    Foo f = dofoo();
        on_scope_failure delete f;
    Bar b = dobar();
        on_scope_failure delete b;
    Def d = dodef();
        on_scope_failure delete d;
    return Transaction(f, b, d);
}

Scaling it up is as easy as linearly adding more on_scope statements, and 
easy to get it right. 





More information about the Digitalmars-d mailing list