Recommended way to do RAII cleanly
Jonathan M Davis
jmdavisprog at gmail.com
Mon Jul 12 01:38:43 PDT 2010
On Sunday 11 July 2010 23:41:21 Lars T. Kyllingstad wrote:
>
> That said, the recommended best practice for D is, if possible, to use
> scope guards:
>
> void doStuffWith(string resourceName)
> {
> auto resource = acquire(resourceName);
> scope(exit) release(resource);
>
> ... // Do stuff with resource here
> }
>
> -Lars
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.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list