Scope guards

Cecil Ward cecil at cecilward.com
Mon Jun 26 18:42:25 UTC 2023


On Monday, 26 June 2023 at 17:41:16 UTC, Paul Backus wrote:
> On Saturday, 24 June 2023 at 17:00:36 UTC, Cecil Ward wrote:
>> I would like to use scope guards but in the guard I need to 
>> get access to some local variables at the end of the routine. 
>> This doesn’t really seem to make sense as to how it would 
>> work, because their values depend on the exact point where the 
>> scope guard is called at in the last, exiting line(s) of the 
>> routine. Am I misunderstanding?
>
> Scope guards are syntax sugar for try/catch/finally. For 
> example, when you write
>
>     auto f = open("foo");
>     scope(exit) close(f);
>     doSomethingWith(f);
>
> ...it gets transformed by the compiler into
>
>     auto f = open("foo");
>     try {
>         doSomethingWith(f);
>     } finally {
>         close(f);
>     }
>
> I do not understand exactly what the problem is you are having, 
> but hopefully this lets you figure out how to solve it.

Sorry for being stupid, but say you have something like this

==
{
size_t p = offset;
++p;
scope(exit) { writeOutput( 0, p );

++p
…
++p;

return;
}

==

The correctness of its behaviour depends on what the value of p 
is when it calls writeOutput(), and the value of p is being 
changed. To be correct, the final value of p needs to be passed 
to writeOutput( p ). That was what I was worrying about. I could 
have course introduce another variable to capture this final 
value and use that in the scope guard, but then I can’t make the 
scope guard general if I have more than one exit route. The 
compiler sounded as if it did not like the local variable p in 
the scope guard, but I need to try it again to get the error 
message.


More information about the Digitalmars-d-learn mailing list