0

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';


}
Russell Greene
  • 2,141
  • 17
  • 29

1 Answers1

7

This has nothing to do with lambdas, regular functions can return references to destructed variables too. And like lambdas, it's undefined behavior, and the numbers have random values and/or crash.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • So the fact that the same function, except using `a++` instead of `a` and then calling `fun()` multiple times gives incrementing numbers is an anomaly , it might not work if the stack is used much after that? – Russell Greene Apr 25 '15 at 01:14
  • 2
    @RussellGreene Correct. These anomalies can go pretty far before crashing. I prefer to avoid positive statements like "It has a random value." It's more like, "It's not guaranteed to work or to fail, and any failure may manifest in a random way." – Potatoswatter Apr 25 '15 at 01:25