I'm just starting to learn new features in C ++ 11. I read about lambdas in C ++ Primer (Stanley Lippman) and experimented with them.
I tried the following code snippets:
auto func() -> int (*) (){ //int c=0; return []()-> int {return 0;}; } int main(){ auto p = func(); }
This code is compiled. Therefore, I believe that lambdas without any captures are generated as normal functions by the compiler, and we can use a regular pointer to them.
Now I changed the code to use captures:
auto func() -> int (*) (){ int c=0; return [=]()-> int {return c;}; } int main(){ auto p = func(); }
But this could not be compiled. When using g ++, I got the following compilation error:
main.cpp: In function 'int (* func())()': main.cpp:6:31: error: cannot convert 'func()::__lambda0' to 'int (*)()' in return return [=]()-> int {return c;};
From the error, I can understand that this is not a normal function that is generated, and perhaps this is a class with an overloaded call statement. Or is it something else?
My questions: How does the compiler handle lambdas internally? How should I go around lambdas that use captures, i.e. what should the func () return value be? I canβt think about a use case where I will need to use lambdas, but I just want to learn more about them. Please, help.
Thanks.
c ++ lambda c ++ 11
Madhusudhan
source share