Understanding the D memory model re: Voldemort types

Matt Kline via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 9 11:08:17 PDT 2015


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?


More information about the Digitalmars-d mailing list