Recommended way to do RAII cleanly

Simen kjaeraas simen.kjaras at gmail.com
Mon Jul 12 12:18:38 PDT 2010


Jonathan M Davis <jmdavisprog at gmail.com> wrote:

> Except that that's two statements and it's no longer RAII. The beauty of  
> doing
> it entirely in the constructor and destructor is that you only need one
> statement and the whole thing takes care of itself. With scope, you have  
> to
> worry about remembering to use scope, and even if you do, that's two  
> statements
> instead of one. Obviously, it works, but it's not as clean or elegant.

So use an enum and string mixins:

import std.stdio;

enum bar = q{
     writeln( "The bar has opened." );
     scope( exit ) {
         writeln( "The bar has closed." );
     }
};

void main( ) {
     writeln( "Entering..." );
     mixin( bar );
     writeln( "Exiting..." );
}

Output:
Entering...
The bar has opened.
Exiting...
The bar has closed.

-- 
Simen


More information about the Digitalmars-d-learn mailing list