C++11 lambdas are great!
But one thing is missing, which is how to safely deal with mutable data.
The following will give bad counts after the first count:
In f1
you're getting undefined behavior for the reason you say; the lambda contains a reference to a local variable, and after the function returns the reference is no longer valid. To get around this you don't have to allocate on the heap, you simply have to declare that captured values are mutable:
int k = 121;
return std::function([=]() mutable {return k++;});
You will have to be careful about using this lambda though, because different copies of it will be modifying their own copy of the captured variable. Often algorithms expect that using a copy of a functor is equivalent to using the original. I think there's only one algorithm that actually makes allowances for a stateful function object, std::for_each, where it returns another copy of the function object it uses so you can access whatever modifications occurred.
In f3
nothing is maintaining a copy of the shared pointer, so the memory is being freed and accessing it gives undefined behavior. You can fix this by explicitly capturing the shared pointer by value and still capture the pointed-to int by reference.
std::shared_ptr o = std::shared_ptr(new int(k));
int &p = *o;
return std::function([&p,o]{return p++;});
f4
is again undefined behavior because you're again capturing a reference to a local variable, o
. You should simply capture by value but then still create your int &p
inside the lambda in order to get the syntax you want.
std::shared_ptr o = std::shared_ptr(new int(k));
return std::function([o]() -> int {int &p = *o; return p++;});
Note that when you add the second statement C++11 no longer allows you to omit the return type. (clang and I assume gcc have an extension that allows return type deduction even with multiple statement, but you should get a warning at least.)