auto fnc()
{
int x = 0;
auto clos = [&]() { return ++x; };
return clos;
}
#include <iostream>
int main()
{
auto clos = fnc();
for (int i=0; i<5; ++i) std::cout << clos() << '\n';
}
This seems work only if var x would be static. But I thought that for a closure the variables needn't to be static.
Another question is: What would the type of such a lambda function be (so when I would replace all 'auto')?
You're capturing by reference (the [&] bit), and that does not extend the lifetime of the captured variable. The closure object is returned from fnc, while x is destroyed, and so the closure is holding a dangling reference.
Either capture by value auto clos = [=]() mutable { return ++x; }; or make sure the lifetime of x encloses the lifetime of the closure object (making x static is the ultimate way to do that)
What would the type of such a lambda function be (so when I would replace all 'auto')?
each lambda expression produces a result of a unique type, which cannot be named. It can be deduced with auto, or wrapped in std::function