Understanding the D memory model re: Voldemort types
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Thu Apr 9 11:12:37 PDT 2015
On Thu, Apr 09, 2015 at 06:08:17PM +0000, Matt Kline via Digitalmars-d wrote:
[...]
> 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?
The compiler detects when a variable is being closed over by a nested
function, and allocates them on the heap instead of the stack.
T
--
Computerese Irregular Verb Conjugation: I have preferences. You have biases. He/She has prejudices. -- Gene Wirchenko
More information about the Digitalmars-d
mailing list