(Adding information from the related questions suggested with the answer to the replica of the question on the English site , I came to the following conclusion :)
When declaring a lambda, the compiler generates the equivalent of a new type, of indefinite and unique name, that has a operador()
containing the body of the function that defines it.
If a lambda does not catch variables, C ++ allows this to fall to an ordinary pointer for this function (and this conversion is invoked when applying operador+
, returning its address).
As functions are stored in a separate area of memory - all functions in C ++ are - the pointer remains valid throughout the execution of the program, and the destruction of the function never happens (just as a class is never destroyed, only objects / instances of this). This allows you to return the pointer to a local lambda as well, as in the following example :
#include <iostream>
bool (*cpp_newbie())()
{
auto a = +[]{return true;};
return a;
}
int main()
{
auto a = cpp_newbie();
std::cout << std::boolalpha << a();
}
This seemed counterintuitive to me at first, but it became clear to realize that lambda defines a type, and the a
object in question is just a pointer to a "member function", so to speak. / p>