Do anonymous function are persistent in memory, or are they pass by value

151 Views Asked by At

In C++ when we do something like this :

void a_function(void (*function_name)(char *data))
{
    char *data = new char[1];
    function_name(data);
}

a_function([](char *data) {
    //do sth
});

I guess function_name is a pointer to a function. But when I pass an anonymous function, is a space in the memory allocated for this function before being passed?

If I didnt pass an anonymous function but did pass address of an existing function, would it be an equal case to the code piece above ?

1

There are 1 best solutions below

0
On BEST ANSWER

In practice, the stateless lambda has a function that exists so long as the compiler cannot prove nobody calls it. This function is stored in your executable at compile time, and is loaded at run time. Barring a dll or so format (or other similar things), it lives as long as the program does.

In theory, there are valid function pointers that when invoked run a function. The pointer you get from a stateless lambda is a valid function pointer, and it does not become invalid when the lambda it is created from is destroyed.