A delegate problem, create delegation in loop

lijie cpunion at gmail.com
Wed Jul 4 22:54:05 PDT 2012


Hi,

My test code:


> import std.stdio;
> void main() {
>     void delegate()[] functions;
>     foreach (i; 0 .. 5) {
>         functions ~= {
>             printf("%d\n", i);
>         };

    }
>     foreach (func; functions) {
>         func();
>     }
> }


output:

$ dmd

DMD64 D Compiler v2.059

...

$ ./main
> 5
> 5
> 5
> 5
> 5


Seems like all delegations shared a stack variable, I think delegation must
copy the value into its context.

I can avoid it:

    void delegate() createDelegate(int i) {
>         void exec() {
>             printf("%d\n", i);
>         }
>         return &exec;
>     }
>     foreach (i; 0 .. 5) {
>         functions ~= createDelegate(i);
>     }


But hope for improve it.


Best regards,

-- Li Jie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20120705/40b5cfef/attachment.html>


More information about the Digitalmars-d mailing list