(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.