vendredi 24 avril 2015

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

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.

Aucun commentaire:

Enregistrer un commentaire