If I have some c++ code that looks roughly like this:
void (*fun_ptr)(int);
void Test()
{
fun_ptr = [](int i) { /* do stuff */ };
}
int main()
{
Test();
/* do stuff */
fun_ptr(0);
return 0;
}
Can I expect that function pointer to live forever? Or is it like structs and it’s only valid for as long as the lambda declaration is within scope?
The linked answer does not fully adress this question, the linked answer does not explain why scoped lambdas can outlive the scope of the code that created them.
>Solution :
fun_ptr doesn’t point to a lambda.
It effectively points to a static function (defined in the lambda class), and this function doesn’t need a living lambda to work.