2

I'm new to C++. I was messing around with lambdas and gcc compiler threw an error. Can someone kindly explain why it's happening?

Compilable code:

int main() {
    int abc= 456;
    int* abc_ptr= &abc;
    auto lambda= [abc_ptr]() { *abc_ptr= 123; };    // Works fine
    lambda();
}

This does not work however:

int main() {
    int abc= 456;
    int* abc_ptr= &abc;
    void (*lambda)()= [abc_ptr]() { *abc_ptr= 123; };    // error: cannot convert 'main()::<lambda()>' to 'void (*)()' in initializationx86-64 gcc 11.2 #1
    lambda();
}

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 6
    Only capture-less lambdas can be converted to a pointer to a function. – Some programmer dude Dec 22 '21 at 07:54
  • 2
    To be more specific, a lambda is not really a function in itself. Rather the compiler will create an object of a unique class, with a suitable function-call operator. This object can have a conversion-operator to a pointer to function, but only if the lamda doesn't have any captures (the list inside the `[` and `]`). – Some programmer dude Dec 22 '21 at 07:56
  • 1
    Related: https://stackoverflow.com/q/28746744/3455688 – Dragoner Dec 22 '21 at 08:03
  • 1
    Just for completeness, you could assign your lambda to `std::function ` if that's what you want (so that you can store it in a member variable, for instance). – Paul Sanders Dec 22 '21 at 08:20
  • @PaulSanders But using std::function generates "much" overhead... if not needed ( because not mixing a lot of different pointer types ) you als can simly write `auto lambd= [](){}:' – Klaus Dec 22 '21 at 08:33
  • @Klaus Sure, you would only use it when you needed to. – Paul Sanders Dec 22 '21 at 08:34

0 Answers0