C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::recurse

From: Jeremy Rifkin <rifkin.jer_at_[hidden]>
Date: Sun, 18 May 2025 14:41:21 -0500
> well on x86_64 when a member function is invoked, the
'this' pointer is placed in the RDI

By the time std::recurse is called it could be anywhere (or nowhere).

Keep in mind lambdas operator()'s might be static, too, and normal
functions won't have `this` pointers.

Jeremy



On Sun, May 18, 2025 at 2:18 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:

> On Sun, May 18, 2025 at 5:38 PM Frederick Virchanza Gotham wrote:
> >
> > std::this_pointer();
>
> Just thinking now, it might be possible to implement this without
> compiler magic.
>
> If you need a quick and dirty way to get the 'this' pointer inside a
> lambda function, well on x86_64 when a member function is invoked, the
> 'this' pointer is placed in the RDI register (or RCX on MS-Windows),
> so you can do this:
>
> #include <iostream>
>
> int main(void)
> {
> // Define a lambda function
> auto lambda = []()
> {
> void *rdi;
> asm ("mov %%rdi, %0" : "=r" (rdi));
> std::cout << rdi << std::endl;
> };
>
> lambda();
> std::cout << &lambda << std::endl;
> }
>
> You can do something similar for every architecture pretty much
> (although it will be a little trickier if it's on the stack -- but
> even then, it will be only two slots away from the current stack
> pointer, as the 1st slot is the return address, and the 2nd slot will
> be for the left-most parameter). So the implementation of
> "std::this_pointer" might not need any compiler magic on any platform.
> Maybe. The optimiser might screw this up if, for example, it re-uses
> the RDI register (which is caller-saved).
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2025-05-18 19:41:34