(gathering information from related questions suggested with the answer to replica of the question on the website in English, I came to the following conclusion:)
When declaring a lambda, the compiler generates the equivalent of a new type, with an undefined and unique name, which has a operador()
containing the body of the defining function.
If a lambda does not capture variables, C++ allows it to decay to an ordinary pointer for this function (and this conversion is invoked when applying the operador+
, returning your 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 it). This allows you to even return the pointer to a local lambda, 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 at first, but it became clear that lambda defines a type, and the object a
in question is only a pointer to a "member function", so to speak.
It seems to me that in automatic storage ("stack"), and that it does not necessarily decay, but rather can be converted into pointer to function, but whether or not it can be used in C-style calls is dependent on implementation. Stay tuned, because the behavior observed in an implementation is not necessarily the way it will always be.
– Pablo Almeida
Thanks. I’m researching the answers and it seems that Amblas has some freedom of implementation... If this proves true, I will ask you to elaborate the comment in response.
– Kahler