anonymous functions and scope(exit)

jfondren julian.fondren at gmail.com
Sun Jul 4 10:07:08 UTC 2021


On Sunday, 4 July 2021 at 08:24:36 UTC, Luis wrote:
> On Saturday, 3 July 2021 at 22:52:39 UTC, frame wrote:
>>
>> It works if you replace printf() with writeln() or use 
>> writeln() after. There must be some buffer issue.
>
> Not works as you expected.
> Yes, replacing by writeln (better said, putting a writeln) 
> makes it to work. More weird,

Dennis's explanation makes the most sense:

writeln can throw an Exception, so its presence prevents nothrow 
inference, which otherwise permits the (not intended to be 
catchable) RangeError to exit without properly unwinding the 
stack.

By that, what you're running into is an unpleasant interaction 
between
1. scope(exit)s that you're writing
2. Errors being thrown rather than Exceptions
3. anonymous functions getting inferred as nothrow

And a resolution could be to submit an issue to make #1 prevent 
#3: if someone wants nothrow on an anonoymous function with scope 
guards, they have to make it explicit.

And while checking for prior issues like this, I found

https://issues.dlang.org/show_bug.cgi?id=17494

>Not cleaning up after an Error is thrown is allowed by the D 
>spec. This enhancement allows much better code to be generated 
>for `nothrow` code when `scope` is used. It will also not unwind 
>declarations with destructors in `nothrow` code when Errors are 
>thrown.

I read this initially as "it is a bug for scope(exit) to ever run 
after an Error is thrown", but it's an optimization for nothrow 
code, which fits what you're seeing.



More information about the Digitalmars-d-learn mailing list