I have a bit of confusion about the D memory model when it comes
to returning nested classes (i.e. "Voldemort types") and am
hoping someone can take a minute to clear it up. Consider the
following short program:
auto foo()
{
import std.random;
import std.conv;
auto i = dice(0.5, 0.5);
string s = "Hello, scopes";
class Bar {
string what() { return s ~ " " ~ i.to!string; }
}
return new Bar;
}
void main()
{
import std.stdio;
auto b = foo();
writeln(b.what());
}
I was under the impression that nested classes captured their
context via a pointer to the current stack frame. But if that
were the case, reading i and s when b.what() is called would
cause invalid reads below the current stack pointer, and this
data could be thrashed by inserting any calls between the call to
foo() and the call to b.what(). Running the above program through
valgrind also indicates no foul play.
So what is actually going on here? Do nested classes capture
their context some other way? Does the compiler do semantic
analysis and capture local variables by value if an instance of
the Voldemort type is going to get returned out of the function?