Zoran Isailovski wrote:
I'm an experienced C#, Java and Python programmer, and have employed closures
(and C# delegates) upon numerous occasions. While experimenting with D closures
and delegates, I was stroke by a phenomenon I cannot explain. Here's the code:
[snip]
Handler incBy(int n)
{
return delegate(int arg){ return arg + n; };
}
[snip]
/* **************************************** *
* Compiled with: Digital Mars D Compiler v1.030
*
* (Unexplainable) program output:
[snip]
What goes wrong???
Dv1.x doesn't automatically allocate closures for escaping delegates, so
the storage used for parameter "n" is getting overwritten when another
function is called.
Try the latest v2.x compiler, or explicitly copy the parameter to the heap.