Search code examples
c++lambdac++-amp

Can I run a stored lambda whose captured values are no longer in scope?


I have a future to which I want to pass a lambda to run when it is complete, but the scope will have changed by the time the lambda executes; what happens to the captured value? For example

bool* MakeThen(Concurrency::completion_future& future)
{
  bool * isFinished = new bool(false);
  future.then([=](){ *isFinished = true; });

  return isFinished;
}

By the time that lambda actually executes, the function might have finished. So what will happen? Is capturing by value just like binding a bunch of variables?


Solution

  • Your lambda captures the isFinished pointer by value, and the object to which it points is on the free store. So it's fine. There is no local object being referred to in the lambda.