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();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With