Delegate is left with a destroyed stack object

Ali Çehreli acehreli at yahoo.com
Tue Oct 29 14:57:25 PDT 2013


On 10/29/2013 02:41 PM, David Nadlinger wrote:

 > Closures follow the infinite lifetime model – the struct scope is never
 > left, if you want.

Agreed but the implicit nature of things is troubling. Imagine that the 
program depends on the destructor to be called:

void foo()
{
     auto s = S(1);
     // ...
}

Later, somebody creates a lambda that silently extends the lifetime of 
the stack frame (apparently, infinitely). That may be very surprising.

Aside: Is it still a closure if the lambda does not refer to the stack 
frame? If so, it is even worse:

import std.stdio;

struct S
{
     int i;
     ~this() { writeln("dtor"); }
}

void bar()
{}

auto foo()
{
     S s = S(1);
     return &bar;    // <-- all is well, this is not a closure
}

void main()
{
     foo()();
}

Imagine someone decides to return a lambda from foo() instead:

auto foo()
{
     S s = S(1);
     return {};    // <-- Should 's' be immortal now?
}

Too subtle for my taste! :)

 > This is not exactly a new scenario, destructors on new'd structs aren't
 > called either (unless you manually destroy them).

At least in the case of a new'ed structs I have a convenient way to 
destroy them through a pointer. I think in the case of a closure I must 
go through hoops to access or save that pointer.

Ali



More information about the Digitalmars-d mailing list