[Issue 2043] Closure outer variables in nested blocks are not allocated/instantiated correctly.

d-bugmail at puremagic.com d-bugmail at puremagic.com
Fri Aug 15 05:21:17 PDT 2008


http://d.puremagic.com/issues/show_bug.cgi?id=2043





------- Comment #3 from brunodomedeiros+bugz at gmail.com  2008-08-15 07:21 -------
(In reply to comment #2)
> Here's a better illustration of the problem:
> void delegate() dg;
> void main()
> {
>     foreach(int i; 0 .. 2)
>     {
>         invariant int b = i;
>         if (i == 0)
>             dg = { printf("b = %d\n", b); };
>         dg();
>     }
>     dg();
> }
> 'b' is supposed to be invariant, yet its value (as seen by dg()) changes. One
> possible fix for this is to make invariants that are initialized with varying
> values be illegal to reference from a delegate.


I'm assuming that a variable declared inside a loop conceptually represents not
a single variable that gets reinitialized with each iteration, but instead
represents several different variable "instances" (so to speak), each "created"
in each iteration. I vaguely recall you confirming this notion (which is indeed
what makes more sense and is more consistent), but I can't pinpoint the
comment.

Given that assumption, then your code is *not* a better illustration of the
problem. This isn't specific to invariant, and the problem is not exactly that
b's invariance is broken, but rather that D fails to create several "instances"
of b. In other words, I would expect your example to work the same as this
code:

-----------

void delegate() dg;

void foreachBody(int i) {
    invariant int b = i;
    if (i == 0)
        dg = { printf("b = %d\n", b); };
    dg();
}

void main(string[] args) 
{
    foreach(int i; 0 .. 2)
       foreachBody(i);
    dg();
}

-----------
I hope the example above clarifies what I mean by saying that b (and any
variables inside the loop) should be "different" variables every time the scope
is entered.


-- 



More information about the Digitalmars-d-bugs mailing list