Delegate is left with a destroyed stack object
Ali Çehreli
acehreli at yahoo.com
Tue Oct 29 10:55:43 PDT 2013
Continuing the conversation from the following thread:
http://forum.dlang.org/post/l4mi8l$1r1$1@digitalmars.com
(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?
Aside: Never mind that the destroyed object gets destroyed again, and
again, and again. :) (Well, presumably after being copied to other
object in its dead state, because the address of the object is not the
same.) (Put a writeln() inside the destructor to see that in action.)
Ali
More information about the Digitalmars-d
mailing list