www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Re: confusing (buggy?) closure behaviour

Sergey Gromov Wrote:

 Sat, 13 Dec 2008 06:59:51 -0500, Zoran Isailovski wrote:
 
 Anyway, following the latter pattern, you don't need global analysis.
 You can determine if n is on the stack (it is - it's an argument),
 you can determine if it's referenced from within the closure (it is),
 and you can determine if the closure is being returned (it is). The
 compiler should IMO then generate an error (or warning) about the
 return statement, perhaps stating something like "cannot return a
 delegate that refers to variables in local scope", or something like
 that.

There was a long discussion on this topic. See http://www.digitalmars.com/d/archives/digitalmars/D/Escape_analysis_78791.html for an insight. To summarize, it's almost always potentially unsafe to use stack closures. For instance, if you pass closure to a function, that function can save that closure to a global variable, so the closure outlives the container function without being explicitly returned. If compiler forbids any potentially unsafe use of closures, it would make them next to useless and also would break lots of valid code, for instance a significant part of Tango library.

Thanks for the hint.
Dec 16 2008