https://issues.dlang.org/show_bug.cgi?id=16193
Issue ID: 16193 Summary: opApply() doesn't heap allocate closure Product: D Version: D2 Hardware: x86_64 OS: Linux Status: NEW Severity: normal Priority: P1 Component: dmd Assignee: nob...@puremagic.com Reporter: schue...@gmx.net // yy.d module yy; struct S { int opApply(int delegate(int) dg) { foreach(i; 1 .. 10) { int result = dg(i); if(result) return result; } return 0; } } // xx.d import yy; int* px, py; int foo() { int x = 0, y = 0; foreach(i; S.init) { px = &x; py = &y; y++; } return y; } void main() { import std.stdio; writeln(foo()); int z = 0; writeln("&x = ", px, " &y = ", py, " &z = ", &z); } # dmd -c xx.d # dmd -c yy.d # dmd -ofxx xx.o yy.o # ./xx prints: 9 &x = 7FFEAD3C47C0 &y = 7FFEAD3C47C4 &z = 7FFEAD3C47E8 (or similar) As can be seen, all local variables are allocated next to each other, evidently on the stack. This happens even though S.opApply() doesn't take its delegate as scope. I'm deliberately using separate compilation here to make sure that the compiler has no way to infer that the closure doesn't escape. --