Why is D unpopular, redux.
FeepingCreature
feepingcreature at gmail.com
Tue May 24 07:58:13 UTC 2022
On Tuesday, 24 May 2022 at 07:45:38 UTC, Timon Gehr wrote:
> On 24.05.22 07:31, Walter Bright wrote:
>>
>>> https://issues.dlang.org/show_bug.cgi?id=2043
>>
>> We have better tools to deal with 2043 today. Note that dgList
>> exceeds the lifetime of b, and should fail to compile for that
>> reason.
>>
>> Let's try it (adding import and @safe and updating the code to
>> D2):
>> ----
>> import std.stdio;
>>
>> @safe:
>>
>> void delegate()[] dgList;
>>
>> void test() {
>>
>> foreach(int i; [1, 2, 3]) {
>> int b = 2;
>> dgList ~= { writeln(b); };
>> writeln(&b); // b will be the *same* on each
>> iteration
>> }
>> }
>> ----
>>
>> > dmd test.c -preview=dip1000
>> test.d(13): Error: reference to local variable `b` assigned to
>> non-scope parameter `_param_0`
>>
>> Looks like we can close it now!
>
> No. The correct behavior when a delegate literal outlives
> captured variables is to allocate a closure. This case is not
> an exception...
This is a bit of a controversial topic. Personally I agree that
there should be a closure allocated every loop pass, but *every
other language* allocates them for the whole stackframe, so...
But then handling b is awkward, because the way that compilers
usually square that circle is that they allocate a separate spot
in the stackframe *per variable declaration*, so the loop
variable only gets one distinct declaration. And it's hard
otherwise, because if you allocate a separate frame every loop,
then they can't reference each others' variables. Some languages
solve this by making lambdas unable to write scope variables, but
then obviously they're less useful. Anyway, so in this case the
delegate can't help outlive b *even if* it's closure allocated.
More information about the Digitalmars-d
mailing list