简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM