Delegate is left with a destroyed stack object

Jacob Carlborg doob at me.com
Tue Oct 29 13:23:17 PDT 2013


On 2013-10-29 18:55, Ali Çehreli wrote:
> 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

Shouldn't "s" be moved to the heap and not destroyed.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list