Let's get the semantic around closure fixed.

deadalnix deadalnix at gmail.com
Wed May 19 20:19:22 UTC 2021


On Wednesday, 19 May 2021 at 19:01:59 UTC, Walter Bright wrote:
> On 5/19/2021 10:26 AM, deadalnix wrote:
>> On Wednesday, 19 May 2021 at 13:02:59 UTC, Steven 
>> Schveighoffer wrote:
>>> 2. We need one allocation PER loop. If we do this the way 
>>> normal closures are done (i.e. allocate before the scope is 
>>> entered), this would be insanely costly for a loop.
>> 
>> This is costly, but also the only way to ensure other 
>> invariants in the language are respected (immutability, no 
>> access after destruction, ...).
>> 
>> This is also consistent with what other languages do.
>
> Languages like D also need to be useful, not just correct. 
> Having a hidden allocation per loop will be completely 
> unexpected for such a simple looking loop for a lot of people. 
> That includes pretty much all of *us*, too.
>

It is not surprising that taking a closure would allocate on heap 
if the closure escapes. This is done for functions, this is done 
in every single programming language out there but D, and the 
compiler can remove the allocation if it detect that thing don't 
escape.

In fact, even in C++, you'll find yourself with an allocation per 
loop if you do:

std::vector<std::function<void()>> funs;
for (int i = 0; i < 10; i++) {
     funs.push_back([i]() { printf("%d\n", i); });
}

The instantiation of std::function here will allocate.


More information about the Digitalmars-d mailing list