On Monday, July 12, 2010 12:18:38 Simen kjaeraas wrote: > Jonathan M Davis <[email protected]> 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.
That's a pretty good solution, though it does feel like you're fighting the language when you have to completely change your construct simply because the normal one isn't able to have a version without any arguments to it. I guess that if that's what I have to do, that's what I'll do, but it definitely feels ugly to me in comparison - particularly when I can still use RAII in cases where the constructor does take arguments. - Jonathan M Davis
