scoped chdir and similar patterns
Jonathan M Davis
jmdavisProg at gmx.com
Thu Dec 5 15:07:58 PST 2013
On Thursday, December 05, 2013 07:24:50 qznc wrote:
> On Thursday, 5 December 2013 at 01:07:19 UTC, Timothee Cour wrote:
> > A1.
> >
> > Is there a (clever?) way to achieve the following using a
> > single function
> > call?
>
> You could (mis)use destructors.
>
> =============
> struct chdir_scoped {
> string olddir;
> this(string newdir) {
> olddir = "bar";
> writeln("chdir to "~newdir);
> }
> ~this() {
> writeln("chdir back to "~olddir);
> }
> }
>
> int main() {
> auto x = chdir_scoped("foo");
> writeln("doing work in foo");
> return 0;
> }
> =============
> Output:
> chdir to foo
> doing work in foo
> chdir back to bar
> =============
>
> Feels hacky to me, since "x" is not used anywhere.
That technique is called RAII - Resource Acquisition Is Initialization - and
it's a standard technique in C++ which D's structs also purposefully support.
In C++, without it, having exception-safe C++ is very, very difficult, if not
impossible. Prime examples of it are smart pointers and mutex
autolocks/guards. Unlike C++, D has finally and scope statements (as well as
the GC), which help, but still, RAII is vital for a number of paradigms. I can
understand that it seems a bit weird to have a variable that you declare and
don't do anything else with, but there's nothing hacky about it. It's an
extremely useful and heavily-used paradigm.
https://en.wikipedia.org/wiki/RAII
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list