Comment #0 by dlang-bugzilla — 2015-03-08T08:29:24Z
Illustrative example:
////////////// example.d /////////////
import std.stdio;
auto getLogger()
{
auto f = File("log.txt", "w");
return (string s) => f.writeln(s);
}
void main()
{
auto logger = getLogger();
logger("Hello, world!");
}
//////////////////////////////////////
This will crash because the file is already destroyed by the time the lambda runs.
Test case:
///////////////// test.d ////////////////
struct S
{
int i;
~this() { i--; }
}
auto outerFun()
{
auto s = S(1);
void innerFun() { assert(s.i == 1); }
return &innerFun;
}
void main()
{
auto f = outerFun();
f();
}
/////////////////////////////////////////
Now that we have finalization of structs on the heap, maybe it's time to move closure destruction from end of scope to GC-collection time.
I'm not sure if accessing destroyed objects can be considered a safety problem, but if it is, all the more reason to fix.
Comment #1 by robert.schadek — 2024-12-13T18:41:05Z