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

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Jun 19 09:25:23 PDT 2012


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


timon.gehr at gmx.ch changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |timon.gehr at gmx.ch


--- Comment #7 from timon.gehr at gmx.ch 2012-06-19 09:27:41 PDT ---
(In reply to comment #6)
> ...
> Simplified case, which returns array of delegates each printing next integer.
> 
>   import std.stdio;
>   alias void delegate() D;
>   /* do not work, */
>   auto f(int n) {
>         auto tab = new D[n];
>         for (int i = 0; i < n; i++) {
>                 // invariant ii = i; // will not help
>                 // struct S { int i_; }; S x = new S; x.i_ = i;
>                 // will also not help, as x is on stack
>                 tab[i] = delegate void() { writefln("i=%d", i); };
>                 // also using nested function, and taking address do not work
>         }
>         return tab;
>   }
> 
>   void main() {
>         auto tab = f(10);
>         foreach (k, ref x; tab) {
>                 writef("%d : ", k);
>                 x();
>         }
>   }
> 
> It currently will print in all cases:
> 
>   0 : i=10
>   1 : i=10
>   2 : i=10
>   3 : i=10
>   4 : i=10
>   5 : i=10
>   6 : i=10
>   7 : i=10
>   8 : i=10
>   9 : i=10
> 
> 
> My current workaround involves looping using recursion (and be sure that
> compiler do not make it tail-recursive probably):
> [snip.]

There is a much simpler workaround:

  import std.stdio;
  alias void delegate() D;

  auto f(int n) {
        auto tab = new D[n];
        for (int i = 0; i < n; i++) (){ int i = i;
                tab[i] = delegate void() { writefln("i=%d", i); };
        }();
        return tab;
  }

  void main() {
        auto tab = f(10);
        foreach (k, ref x; tab) {
                writef("%d : ", k);
                x();
        }
  }

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list