The reason is that this behavior is undefined.
Inner lambda captures x by reference.
The problem is that as soon as add() returns, its parameter is destroyed, and the returned lambda has a sagging reference to the destroyed object.
Lambda should fix x by value; and what it seems to me that you are really trying to do here is mutable lambda :
auto add(int x) { function<int(void)> g = [x]() mutable {return ++x;}; return g; }
Note that this approach has certain implications when it comes to subsequent copying of the returned lambda; but as long as the returned lambda stays βin one placeβ, for the rest of your life, the resulting semantics will probably be what you expect.
source share