Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression using scope variables - is safe?

Tags:

c++

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();
like image 353
Evgeny Avatar asked Feb 01 '26 09:02

Evgeny


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.

like image 113
Caleth Avatar answered Feb 04 '26 01:02

Caleth


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();
}
like image 26
Ayxan Haqverdili Avatar answered Feb 03 '26 23:02

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!