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

What is the lifetime of a lambda parameter in C++

How long is a parameter (captured by value) within a lambda expression valid?
Is the parameter valid for the lifetime of the lambda itself, or is it only valid only for the duration of the call?

For example given this:

[value = 5] { DoSomething(&value) }

Does the &value pointer remain valid after the lambda call has finished? (Of course assuming that the lambda itself is still alive.)

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


I’ve seen this similarly named question, but this deals with modifying the lambda inside the expression, not the lifetime.


To answer the comments, I’m also suspecting value is captured as a member (and therefore should remain alive outside the expression). But I’m concerned this might be wrong because value could theoretically be captured as a member but then passed into the expression itself by value (and therefore the reference we see would not remain alive).

>Solution :

A lambda is a shorthand for an anonymous struct with operator() which is automatically generated by the compiler.
The captures are actually data members in this struct.

The pointer &value (which is the address of a data member) is valid as long as the instance of this struct is alive.
It could be after the execution of the lambda.

For example in the following case:

{
   // ...

   auto l = [value]() { DoSomething(&value); };

   // ...
}

the pointer &value that is passed to DoSomething is valid until l goes out of scope at the bottom } and destroyed.

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