Makogan
Makogan

Reputation: 9622

How long does a non capturing lambda live?

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 answer in What is the lifetime of the target of pointer-to-function pointing to a lambda? 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.

Upvotes: 1

Views: 124

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96689

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.

Upvotes: 4

Related Questions