Date: Sun, 18 May 2025 20:18:56 +0100
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::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).
Received on 2025-05-18 19:18:54