lambda expression using scope variables - is safe?

Viewed 73

When f is called, a is already "destructed". Is it safe to use it this way? How does it work?

std::function<void()> f;
{
  int a = some_calc();
  f = [=] { std::cout << a << std::endl; }
}
f();
2 Answers

Is it safe to use it this way?

Yes

How does it work?

The closure object created by that lambda expression has int a as a data member, copy-initialised from the a in that scope.

Here is conceptually what is going on:

#include <functional>
#include <iostream>

int some_calc() {
    // ...
    return 42;
}

int main() {
  std::function<void()> f;
  {
    int a = some_calc();
    class Lambda {
     private:
      int a;

     public:
      Lambda(int const& _a) : a{_a} {}
      void operator()() const { std::cout << a << std::endl; }
    };
    f = Lambda{a};
  }
  f();
}
Related