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