Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading