Summary
In C ++, when I return a lambda from a function that captures a local variable for that function, what exactly happens and why? The compiler (g ++) seems to resolve it, but it gives me different results than I expected, so I'm not sure if this is technically safe / supported.
More details
In some languages (Swift, Lisp, etc.) you can capture local variables in closure / lambda, and they remain valid in scope as long as closure is in scope (I heard lambda over let over lambda "in the context of Lisp.) For example, in Swift, the sample code for what I'm trying to do is:
func counter(initial: Int) -> (() -> Int) {
var count = initial
return { count += 1; return count }
}
let c = counter(initial: 0)
c()
c()
c()
I tried to write the C ++ equivalent as shown below:
auto counter(int initial)
{
int count = initial;
return [&count] () -> int {
count = count + 1;
return count;
};
}
However, I get the result:
auto c = counter(0);
std::cout << c() << std::endl;
std::cout << c() << std::endl;
std::cout << c() << std::endl;
, , , . , :
int count = 0;
auto c = [&count] () -> int {
count = count + 1;
return count;
};
std::cout << c() << std::endl;
std::cout << c() << std::endl;
std::cout << c() << std::endl;
, , , ++, ? , ?