confusing (buggy?) closure behaviour

Zoran Isailovski dmd.zoc at spamgourmet.com
Fri Dec 12 11:21:32 PST 2008


Frits van Bommel Wrote:

> 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.

Thx, Frits, but I'm stll confused. See my response to Denis.


More information about the Digitalmars-d-learn mailing list