<div>Hi,</div><div><br></div><div>My test code:</div><div> </div><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
import std.stdio;<br>void main() {<br> void delegate()[] functions;<br> foreach (i; 0 .. 5) {<br> functions ~= {<br> printf("%d\n", i);<br> };</blockquote><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
}<br> foreach (func; functions) {<br> func();<br> }<br>}</blockquote><div><br></div><div>output:</div><div><br></div><div><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
$ dmd</blockquote><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
DMD64 D Compiler v2.059</blockquote><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
... </blockquote><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
$ ./main<br>5<br>5<br>5<br>5<br>5</blockquote></div><div><br></div><div>Seems like all delegations shared a stack variable, I think delegation must copy the value into its context.</div><div><br></div><div>I can avoid it:</div>
<div><br></div><div><blockquote class="gmail_quote" style="margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left:0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
void delegate() createDelegate(int i) {<br> void exec() {<br> printf("%d\n", i);<br> }<br> return &exec;<br> }<br> foreach (i; 0 .. 5) {<br> functions ~= createDelegate(i);<br>
}</blockquote></div><div><br></div><div>But hope for improve it.</div><div><br></div><div><br></div><div>Best regards,</div><div><br></div><div>-- Li Jie</div>