scope(exit) considered harmful
    Lutger 
    lutger.blijdestijn at gmail.com
       
    Sun Nov  8 14:19:45 PST 2009
    
    
  
Justin Johansson wrote:
...
> If scope(exit) is meant to be some mechanism for saving try/finally
> boiler-plate code, it is a can of worms, otherwise it is a can of
> i-dont-know-what-it's-good-for.
It is that, but also used where you could otherwise use RAII a la C++.
 
> To my way of thinking, and no doubt I should go back to remedial CS-101,
> semantics of scope(exit)  should related to function scope and not
> curly-brace scope-statement scope.
I understand this could possible be tricky but consider this:
- it is in the docs
- the name says it almost literally: scope(exit) means: do this at scope 
exit.
- it behaves the same as try/catch/finally (which introduces a new scope) 
and destructors in C++. 
It is also more expressive than it would be were scope be restricted to 
function scope. 
I can't come up with a real example, but suppose this:
A get_A_or_null()
{
    auto a = null;
    if (takeThisBranch)
    {
        a = new A;
        scope(failure)
            a.cleanup; // segfaults!
        auto b = new B;
        scope(exit)
            b.cleanup(); // Undefined behaviour or compiler error? 
    }
    return a;
}
    
    
More information about the Digitalmars-d
mailing list