Re:Goals and Priorities for C++
by abjKT26nO8 on Friday May 22, 2020 @11:01AM
(#23272817)
At one job I wrote the equivalent of the following (it's just that I invoked create_lambda more times):
#include <functional>
#include <iostream>
std::function<void()> create_lambda(const int& x, const int& y) {
return [&] {
std::cout << "x: " << x << "\n";
std::cout << "y: " << y << "\n";
};
}
int main() {
int x = 5;
int y = 7;
const auto f = create_lambda(x, y);
f();
}
And it crashed. There were no local variables in create_lambda and the lambda crashed in the same function that create_lambda was called in. When I try to reproduce it now, it doesn't work. Not sure what's different, but this is basically what happened.
it doesn't copy the stack pointer, but it enumerates all variables you use and captures a reference to it (I think the &, as used in address-of and references kind of gives it away). [=] {} unsurprisingly captures by value.
Some compilers do warn when you return lambdas capturing local vars by reference, but it is not super reliable.