Search code examples
c++lambdascope

Passing lambda function that captures temporary variable by reference in another function


void func(const int temp) {
  auto lambda_func = [&temp]() {
    return std::make_unique<int>(temp);
  }

  return another_func(lambda_func);
}

In this piece of code, temp is captured by reference in the lambda function and the lambda function is passed as an argument into another_func. I am not sure of what the scope of temp is in this case since it's a reference to a variable that exists only in func.

So once we are inside another_func, does the lambda_func that is passed in still have access to the original temp or does the behavior become undefined?


Solution

  • temp goes out of scope and gets destroyed when execution returns from func.

    func calls another_func. After another_func returns, func itself returns.

    func returns only after execution returns from another_func.

    Therefore, all references to temp remain valid for the entirety of another_func's execution. This object does not go out of scope and get destroyed until after another_func returns.

    Note that if lambda_func, together with its captured by reference object gets copied, or otherwise remains in scope after func returns, then its captured reference now refers to a destroyed object, and any reference to it becomes undefined behavior.