Voldemort type "this" pointer

Ali Çehreli acehreli at yahoo.com
Wed Apr 21 15:53:59 UTC 2021


On 4/21/21 8:37 AM, realhet wrote:
> On Wednesday, 21 April 2021 at 10:47:08 UTC, Mike Parker wrote:
>> On Wednesday, 21 April 2021 at 10:00:51 UTC, realhet wrote:
>>
>>> It has access to the context of its enclosing scope (via an added 
>>> hidden field).
> 
> Thanks!
> 
> So it is unsafe to return a non-static nested struct from a function. 
> But it is useful to pass it forward into other functions.

Not at all. (D is good at preventing such bugs anyway.)

The local context that the nested struct object uses becomes the context 
of that object. Here is a poor person's proof (one can inspect the 
assembly output to observe delegate allocation as well):

import std.stdio;

auto foo() {
   int i;
   writeln(&i, " <- dynamic memory inside foo");

   struct S {
     void bar() {
       writeln(&i, " <- dynamic memory inside bar");
     }
   }

   return S();
}

void main() {
   int m;
   writeln(&m, " <- stack address inside main");
   auto s = foo();
   s.bar();
}

Sample output strongly suggests 'i' is not on the stack because the 
addresses are distant:

7FFFC14D85C0 <- stack address inside main
7FF424B9C008 <- dynamic memory inside foo
7FF424B9C008 <- dynamic memory inside bar

Ali


More information about the Digitalmars-d-learn mailing list