On Tuesday, 29 October 2013 at 17:55:45 UTC, Ali Çehreli wrote:
Continuing the conversation from the following thread:
http://forum.dlang.org/post/[email protected]
(Note: The OP's example there behaves as expected on git head.)
The programmer thinks that the following delegate returned by
foo() will print S(1) because the delegate uses the local 's'
which is supposed to live long enough:
import std.stdio;
struct S
{
int i;
~this() { i = 666; }
}
auto foo()
{
S s = S(1);
return { writeln(s); } ; // <-- Uses local s
}
void main()
{
foo()();
}
However, 's' gets destroyed upon leaving foo() and the delegate
is left with a destroyed object; so the program prints S(666).
Is that by design or a bug?
Seems reasonable to me.
S s = S(1); // allocates on the stack, because value type, i is
now 1
{ 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"
Returning closures with reference to stack memory is a bad idea.
Maybe @safe should prohibit this?