Value closures (no GC allocation)

Vittorio Romeo via Digitalmars-d digitalmars-d at puremagic.com
Sat May 20 21:08:04 PDT 2017


Thanks for the suggestions regarding the `scope` parameter 
attribute. I'll look into it!

On Sunday, 21 May 2017 at 01:30:51 UTC, Adam D. Ruppe wrote:
> On Sunday, 21 May 2017 at 00:49:23 UTC, Stanislav Blinov wrote:
> [...] you *can* write out the struct now, it just has more 
> tedious syntax.

This exact statement applied to C++ before C++11, but the 
introduction of lambda expression significantly changed the way 
people write and think about C++. Sometimes syntactic sugar can 
have huge impact on a language.

I think that creating anonymous structs on the spot (value type 
closures) is not a replacement for the current GC'd closures - it 
has a completely different meaning that can be exactly what you 
need in particular situations, not only for performance-related 
issues. As an example, consider this code:

     void delegate()[] arr;

     foreach(i; 0..5)
     {
         arr ~= () => writeln(i);
     }

     foreach(f; arr)
     {
         f();
     }

This is going to print "4 4 4 4", which might be the desired 
behavior. In other occasions you want to create a closure that 
captures the outer context by value. Here's some example 
pseudocode:

     void value_delegate()[] arr;

     foreach(i; 0..5)
     {
         arr ~= [i]() => writeln(i);
     }

     foreach(f; arr)
     {
         f();
     }

The pseudocode above would explicitly capture `i` by value and 
produce a `struct`-like closure. It would print "0 1 2 3".


More information about the Digitalmars-d mailing list