Where is the function for which a fallen lambda for pointer points stored? How is it released?

3

I recently learned that I can do this:

auto a = +[]{return true;};
a = +[]{return false;};

And I understood that a lambda that does not capture anything may fall to a pointer to function, as confirmed by GCC :

bool (*)()

But where is the actual object to which the lambda points? How is he released? Why can I store a pointer to a temporary object from a lambda? I understand that there is an exotic case in language where a constant reference can extend the life of an object, so I expected the lambda conversion to return something like that, not a pure pointer.

    
asked by anonymous 28.07.2016 / 04:08

2 answers

0

(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>     

28.07.2016 / 10:43
4

According to some answers in a query in SO , a structure with captured data and a form of access is generated. Then an instance is generated for the lambda where the data is stored. Another interesting question with similar content .

The destruction will occur when the variable exits the scope (it can have an extended lifetime depending on how it is used).

In thesis you can put a pointer to that object, just do not know if it's a good idea (of course it depends on what you're going to do with it).

There is a another interesting question in SO linked by Pablo Almeida in comment.

    
28.07.2016 / 04:29