1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. A lambda captures a local int by reference with [&] and is…

Added 30 Nov -0001

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?

  1. It reads a valid value, because std::function extends the lifetime of captures
  2. It reads a dangling reference, because the local died with its stack frame Correct answer
  3. It reads the value the local held, because capture by reference copies on escape
  4. It 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

17 views

MCQSEXAM

Explanation

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.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs