58

I'm trying to figure out how to get the address of a lambda function within itself. Here is a sample code:

[]() {
    std::cout << "Address of this lambda function is => " << ????
}();

I know that I can capture the lambda in a variable and print the address, but I want to do it in place when this anonymous function is executing.

Is there a simpler way to do so?

14
  • 26
    Is this just for curiosity, or is there an underlying problem you need to solve? If there's an underlying problem, please ask about that directly instead of asking about one single possible solution to an (for us) unknown problem. Nov 6, 2019 at 10:55
  • 46
    ... effectively confirming XY-problem.
    – ildjarn
    Nov 6, 2019 at 11:02
  • 9
    You could replace the lambda with a manually written functor class, and then use this. Nov 6, 2019 at 11:10
  • 29
    "Getting the address of a lamba function within itself" is the solution, a solution you narrowly focus on. There might be other solutions, ones that might be better. But we can't help you with that since we don't know what the real problem is. We don't even know what you will use the address for. All I'm trying to do is to help you with your actual problem. Nov 6, 2019 at 11:25
  • 11
    @Someprogrammerdude While most of what you're saying is sensible, I don't see a problem with asking "How can X be done?". X here is "getting the address of a lambda from within itself". It doesn't matter that you don't know what the address will be used for and it doesn't matter that there might be "better" solutions, in someone else's opinion that may or may not be feasible in an unknown code base (to us). A better idea is to simply focus on the stated problem. This is either doable or it isn't. If it is, then how? If not, then mention it isn't and something else can be suggested, IMHO.
    – code_dredd
    Nov 7, 2019 at 21:25

5 Answers 5

59

There is no way to directly get the address of a lambda object within a lambda prior to .

Now, as it happens this is quite often useful. The most common use is in order to recurse.

The y_combinator comes from languages where you could not talk about yourself until you where defined. It can be implemented pretty easily in :

template<class F>
struct y_combinator {
  F f;
  template<class...Args>
  decltype(auto) operator()(Args&&...args) const {
    return f( f, std::forward<Args>(args)... );
  }
  template<class...Args>
  decltype(auto) operator()(Args&&...args) {
    return f( f, std::forward<Args>(args)... );
  }
};
template<class F>
y_combinator(F)->y_combinator<F>;

now you can do this:

y_combinator{ [](auto& self)-> void {
  std::cout<<"Address of this lambda function is => "<< &self;
} }();

There are a few useful variations. One variation I find particularly useful is:

template<class F>
struct y_combinator {
  F f;
  template<class...Args>
  decltype(auto) operator()(Args&&...args) const {
    return f( *this, std::forward<Args>(args)... );
  }
  template<class...Args>
  decltype(auto) operator()(Args&&...args) {
    return f( *this, std::forward<Args>(args)... );
  }
};

where the self passed can be called without passing in self as the first argument.

The second matches the real y combinator (aka the fixed point combinator) I believe. Which you want depends on what you mean by 'address of lambda'.

There is also this pithy one:

template<class R, class...Args>
auto Y = [] (auto f) {
  auto action = [=] (auto action) -> std::function<R(Args...)> {
    return [=] (Args&&... args)->R {
      return f( action(action), std::forward<Args>(args)... );
    };
  };
  return action(action);
};

which returns a std function.


In accessing this within a lambda gets easier:

auto fib = [](this auto& self, int n) {
  if (n < 2) return n;
  return self(n-1) + self(n-2);
};

you can tag the first argument as this, and it becomes itself. It even works with the overload set trick, where self is the most-deduced type.

18
  • 3
    wow, Y combinators are hard enough to wrap your head around in dynamic-typed languages like Lisp/Javascript/Python. I'd never thought I would see one in C++.
    – Jason S
    Nov 6, 2019 at 22:25
  • 14
    I feel like if you do this in C++ you deserve to get arrested
    – user541686
    Nov 7, 2019 at 10:40
  • 3
    @MSalters Uncertain. If F is not standard layout, then y_combinator isn't, so the sane guarantees are not provided. Nov 7, 2019 at 14:05
  • 2
    @carto the top answer there only works if your lambda lives in scope, and you don't mind type erasure overhead. The 3rd answer is the y combinator. The 2nd answer is a manual ycombinator. Nov 7, 2019 at 16:59
  • 3
    @kaz C++17 feature. In 11/14 you'd write a make function, which would deduxe F; in 17 you can deduce with template names (and sometimes deduction guides) Nov 8, 2019 at 3:45
35

It is not directly possible.

However, lambda captures are classes and the address of an object coincides with the address of its first member. Hence, if you capture one object by value as the first capture, the address of the first capture corresponds to the address of the lambda object:

int main() {
    int i = 0;
    auto f = [i]() { printf("%p\n", &i); };
    f();
    printf("%p\n", &f);
}

Outputs:

0x7ffe8b80d820
0x7ffe8b80d820

Alternatively, you can create a decorator design pattern lambda that passes the reference to the lambda capture into its call operator:

template<class F>
auto decorate(F f) {
    return [f](auto&&... args) mutable {
        f(f, std::forward<decltype(args)>(args)...);
    };
}

int main() {
    auto f = decorate([](auto& that) { printf("%p\n", &that); });
    f();
}
13
  • 16
    "the address of an object coincides with the address of its first member" Is it specified somewhere that the captures are ordered, or that there are no invisible members? Nov 6, 2019 at 14:16
  • 36
    @n.'pronouns'm. Nope, this is a non-portable solution. A capture implementation can potentially order the members from largest to smallest to minimize padding, the standard explicitly allows for that. Nov 6, 2019 at 14:30
  • 17
    Re, "this is a non-portable solution." That's another name for undefined behavior. Nov 7, 2019 at 16:50
  • 1
    @ruohola Hard to tell. The "address of an object coincides with the address of its first member" is true for standard-layout types. If you tested whether the lambda's type was standard-layout without invoking UB, you could then do this without incurring UB. The resulting code would have implementation-dependent behavior. Simply doing the trick without first testing its legality is, however, UB.
    – Ben Voigt
    Nov 7, 2019 at 17:55
  • 4
    I believe it is unspecified, as per § 8.1.5.2, 15: When the lambda-expression is evaluated, the entities that are captured by copy are used to direct-initialize each corresponding non-static data member of the resulting closure object, and the non-static data members corresponding to the init-captures are initialized as indicated by the corresponding initializer (...). (For array members, the array elements are direct-initialized in increasing subscript order.) These initializations are performed in the (unspecified) order in which the non-static data members are declared.
    – Erbureth
    Nov 7, 2019 at 18:01
29

One way to solve this, would be to replace the lambda with a hand written functor class. It's also what the lambda essentially is under the hood.

Then you can get the address through this, even without ever assigning the functor to a variable:

#include <iostream>

class Functor
{
public:
    void operator()() {
        std::cout << "Address of this functor is => " << this;
    }
};

int main()
{
    Functor()();
    return 0;
}

Output:

Address of this functor is => 0x7ffd4cd3a4df

This has the advantage that this is 100% portable, and extremely easy to reason about and understand.

1
  • 10
    The functor can even be declared like a lambda: struct { void operator()() { std::cout << "Address of this functor is => " << this << '\n'; } } f;
    – Erroneous
    Nov 6, 2019 at 19:17
-1

Capture the lambda:

std::function<void ()> fn = [&fn]() {
  std::cout << "My lambda is " << &fn << std::endl;
}
3
  • 1
    The flexibility of a std::function is not needed here though, and it comes at considerable cost. Also, copying / moving that object will break it. Nov 7, 2019 at 19:12
  • @Deduplicator why is it not needed, since this is the only anwser that is standard-compliant ? Please give an anwser that works and does not need std::function, then. Nov 8, 2019 at 10:16
  • That seems to be a better and clearer solution, unless the sole point is to get the address of the lambda (which by itself doesn't make much sense). A common use case would be to have access to the the lambla inside itself, for recursion purpose e.g. See: stackoverflow.com/questions/2067988/… where the declarative option as function was widely accepted as a solution :)
    – Abs
    Nov 13, 2019 at 13:12
-7

It is possible but highly depends on the platform and compiler optimization.

On most of the architectures I know, there is register called instruction pointer. The point of this solution is to extract it when we are inside the function.

On amd64 Following code should give you addresses close to the function one.

#include <iostream>

void* foo() {
    void* n;
    asm volatile("lea 0(%%rip), %%rax"
      : "=a" (n));
    return n;
}

auto boo = [](){
    void* n;
    asm volatile("lea 0(%%rip), %%rax"
       : "=a" (n));
    return n;
};

int main() {
    std::cout<<"foo"<<'\n'<<((void*)&foo)<<'\n'<<foo()<<std::endl;  
    std::cout<<"boo"<<'\n'<<((void*)&boo)<<'\n'<<boo()<<std::endl;
}

But for example on gcc https://godbolt.org/z/dQXmHm with -O3 optimization level function might be inlined.

4
  • 2
    I'd love to upvote, but I am not very much into asm and don't understand what is happening here. Some explanation of mechanism how it works would be really valuable. Also, what do you mean by "addresses close to the function"? Is there any constant/undefined offset?
    – R2RT
    Nov 7, 2019 at 13:20
  • 2
    @majkrzak This is not the "true" answer, as it is the least portable of all posted. It's also not guaranteed to return the address of the lambda itself. Nov 8, 2019 at 9:57
  • it states so, but "it is not possible" answer is false asnwer
    – majkrzak
    Nov 8, 2019 at 9:58
  • The instruction pointer cannot be used to derive addresses of objects with automatic or thread_local storage duration. What you are trying to get here is the return address of the function, not an object. But even that won't work because the compiler generated function prologue pushes to the stack and adjusts the stack pointer to make space for local variables. Nov 8, 2019 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.