Problem with closures

Alain alainpoint at yahoo.fr
Thu Jan 11 02:32:42 PST 2007


Frits van Bommel Wrote:

> Alain wrote:
> > AddFunc addN(int n) {
> >     int add(int i) {
> >         return i + n;
> >     }
> >     return &add; // the add function captured will remember the value of n
> > }
> [snip]
> > Am i missing something?
> 
> You shouldn't return delegates to nested functions, just like you 
> shouldn't return pointers to local variables.
> Delegates to nested functions contain a pointer to the stack frame of 
> the enclosing function. If that function has returned, the stack frame 
> may be corrupted (especially if you have called another function, like 
> apply(), since then).

How come this compiles? Is it a bug ?

Alain


More information about the Digitalmars-d-learn mailing list