scoped chdir and similar patterns

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 4 17:14:32 PST 2013


On Wednesday, December 04, 2013 17:07:03 Timothee Cour wrote:
> A1.
> 
> Is there a (clever?) way to achieve the following using a single function
> call?
> 
> //does chdir
> 
> void fun(){
> ...
> string dir0=getcwd; scope(exit) chdir(dir0); chdir(dir);
> ...
> }
> 
> //desired:
> void fun(){
> ...
> chdir_scoped(dir);
> ...
> }

Sounds like a job for RAII. e.g.

{
    auto tcd = TempCD(dir);
    // do stuff
} //tcd leaves scope and its destructor resets the cwd to what it was

In general, I'd say that scope statements are for situations where you
don't have to do the same thing in very many places, whereas RAII is better
when you have to do the exact same thing in several places.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list