Voldemort type "this" pointer

realhet real_het at hotmail.com
Thu Apr 22 09:47:24 UTC 2021


On Wednesday, 21 April 2021 at 15:53:59 UTC, Ali Çehreli wrote:
> 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.

Wow, this information is really out of the box for me. I have one 
misconception less now.
(I never used a language with GC before and this thing requires a 
GC for sure.)

/-------------------------------------------------------
auto uiDeclare(void delegate() fun){
     struct UiObject{
         //void delegate() fun; <- not needed, it captures fun in 
the params
         void render(){ fun(); }
     }
     return UiObject();
}

long rec(long a, long c){ return a<c ? rec(a+1, c) : a; }

void main() {
     int a = 5;
     auto b = [ uiDeclare({ writeln("boop", a); }), uiDeclare({ 
writeln("boop", a+1); })];
     rec(0, 123456); // destroy the stack to make sure
     b.each!"a.render";
}

Indeed it's not using the stack. And it also works when a 
delegates captures its scope.
In my immediate GUI interface I'm using delegates all the time 
with the my misconception of I only allowed to call them from 
inside the function I passed them into.
For example: Row({ Text(clBlue, "Hello"); 
Img(`pictures\pic1.jpg`); }); will call the delegate from inside, 
not save it for later use.

And if I save the delegate inside the Row() function (I mark UI 
generating functions with a capital letter), it is protected from 
the GC and can be used later in rendering time... Too bad, the 
data it uses at that later moment is possibly changed already.

Anyways, I've learned a lot now. Thank you!


More information about the Digitalmars-d-learn mailing list