(I have read What is the lifetime of lambda-derived implicit functors in C++? already and it does not answer this question.)
I understand that C++ lambda syntax is just sugar for making an instance of an anonymous class with a call operator and some state, and I understand the lifetime requirements of that state (decided by whether you capture by value of by reference.) But what is the lifetime of the lambda object itself? In the following example, is the std::function instance returned going to be useful?
std::function<int(int)> meta_add(int x) {
auto add = [x](int y) { return x + y; };
return add;
}
If it is, how does it work? This seems a bit too much magic to me – I can only imagine it working by std::function copying my whole instance, which could be very heavy depending on what I captured – in the past I’ve used std::function primarily with bare function pointers, and copying those is quick. It also seems problematic in light of std::function‘s type erasure.
The lifetime is exactly what it would be if you replaced your lambda with a hand-rolled functor:
The object will be created, local to the
meta_addfunction, then moved [in its entirty, including the value ofx] into the return value, then the local instance will go out of scope and be destroyed as normal. But the object returned from the function will remain valid for as long as thestd::functionobject that holds it does. How long that is obviously depends on the calling context.