I was messing around with lambdas and std::functions the other day, and found a strange property. They still work after captured variables go out of scope.
Here's an example to illustrate what I mean.
#include <iostream>
#include <functional>
std::function<void()> make_lambda()
{
int a = 10;
return [&a](){std::cout << a << std::endl;};
}
int main()
{
auto fun = make_lambda();
fun();
}
To me, it seems that this shouldn't work, a
is captured by reference, and the reference has disappeared.
Edit:
Ok. This problem isn't only with lambada, it is with all references that deleted before use.
My question has changed. I still get similar behavior with extensive stack use, which must be overriding the old data. Here's my new code:
#include <iostream>
int& make()
{
int a = 10;
return a;
}
void flushStack(long long i)
{
if (i == 0)
{
return;
}
flushStack(i-1);
}
int main()
{
int& i = make();
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
flushStack(5000000);
std::cout << "\n\n\n";
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
std::cout << i++ << '\n';
}