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


timon.g...@gmx.ch changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |timon.g...@gmx.ch


--- Comment #7 from timon.g...@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: -------

Reply via email to