Closures and loop scope

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jul 23 07:52:01 PDT 2013


On Tue, Jul 23, 2013 at 03:37:24PM +0200, JS wrote:
[...]
> It is wrong to use a local variable inside a delegate when the
> delegate is called outside the scope of that variable. This should
> technically be an error as it is undefined behavior.

That's not true. According to TDPL, the compiler should detect such
references, and allocate these variables on the heap instead of the
stack, so that the delegate acts like a closure. The variables will be
GC'd once the delegate is no longer used.

This is part of what makes delegates so powerful -- you can use them to
capture the local context of a function and, in effect, access that
context long after the function call has finished.


> I imagine the compiler isn't smart enough to know that you are
> storing delegates to be used outside the scope of i.
[...]

It should know (and in fact does, at least in the simple cases I tried).
If it doesn't, that's a bug that should be filed in bugzilla.


T

-- 
PNP = Plug 'N' Pray


More information about the Digitalmars-d mailing list