On Tuesday, 29 October 2013 at 21:14:39 UTC, qznc wrote:
{ writeln(s); } // creates closure with reference to stack memory "&s" return ... // returns and destroys local variable s, i is now 666
foo()() // calls closure with reference to invalid memory "&s"

That's not how closures work in D – the local variables referenced by nested functions/closures will be allocated inside the "nested context" for the function, which is placed on the GC heap if a reference to it can be escaped. Play around with the example some more if you want: Barring any further DMD bugs, you are not going to get the contents of i to be corrupted (i.e. set to another garbage value).

The problem with the compiler behavior for the code in question is that it destructs a live object, and thus clearly breaks the type system.

I think the only correct resolution is to not destruct the object at the end of foo() – which incidentally also means that the destructor will never be invoked, just as for any other GC-finalized memory.

David

Reply via email to