c++ - Why do std::functions created from lambdas work after captured variables go out of scope? -


i messing around lambdas , std::functions other day, , found strange property. still work after captured variables go out of scope.

here's example illustrate mean.

#include <iostream> #include <functional>  std::function<void()> make_lambda() {     int = 10;      return [&a](){std::cout << << std::endl;}; }  int main() {    auto fun = make_lambda();    fun();  } 

to me, seems shouldn't work, a captured reference, , reference has disappeared.

edit:

ok. problem isn't lambada, references deleted before use.

my question has changed. still similar behavior extensive stack use, must overriding old data. here's new code:

#include <iostream>  int& make() { int = 10;   return a; }  void flushstack(long long i) {   if (i == 0)   { return;   }   flushstack(i-1); }  int main() {    int& = 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';   } 

this has nothing lambdas, regular functions can return references destructed variables too. , lambdas, it's undefined behavior, , numbers have random values and/or crash.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -