A lambda captures a local int by reference with [&] and is stored in a std::function that outlives the enclosing function. What happens when it is invoked later?
AIt reads a valid value, because std::function extends the lifetime of captures
BIt reads a dangling reference, because the local died with its stack frameCorrect answer
CIt reads the value the local held, because capture by reference copies on escape
DIt throws std::bad_function_call, since the captured reference has expired
Correct answer
B. It reads a dangling reference, because the local died with its stack frame
Lambda capture by reference stores only the address of the local, so once the enclosing function returns the closure holds a dangling reference and invoking it is undefined behaviour. Capturing by value, or capturing a shared_ptr, keeps the data alive for as long as the closure exists. The compiler cannot diagnose the escape, though static analysers flag it.