@nogc closures

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 5 10:57:32 UTC 2018


On 8/5/18 5:20 AM, vit wrote:
> It's possible create something like this without errors?
> 
> void main()@nogc{   //Error: function `app.main` is `@nogc`
>                      //  yet allocates closures with the GC
>      import std.experimental.all;
> 
>      const int j = 2;
>      int i = 0;
>      const int[3] tmp = [1, 2, 3];
> 
>      tmp[]
>          .filter!((x)scope => x == j)    ///main.__lambda1 closes over 
> variable j
>          .each!((x)scope => i = x);
> }

The issue is that filter returns a struct with the lambda in it. (the 
FilterRange). So the compiler can't deduce that the lambda never escapes.

Note, in your toy example, you can fix it by making j an enum, but I'm 
assuming this isn't possible in the real code.

-Steve


More information about the Digitalmars-d-learn mailing list