Today I met very unintuitive behavior (at least for me) in C ++ 11 lambdas. This code is as follows:
#include <stdio.h> auto sum(int x) { return [&x](int y) { return x + y; }; } int main() { int a = sum(2)(3); printf("%d\n",a); }
Instead of printing 5, it prints gibberish. In fact, at least in my version of GCC, if I turn on the OO optimization flag, it actually prints 5. Since the output depends on the compiler optimization level, this behavior is undefined. After a while, I think I realized what was going on.
When the sum function is called, the stack variable corresponding to the argument x is set to 2, then the sum function is returned, and this stack variable can be overwritten by everything that the compiler must execute there in order to execute the following code, and by the time the lambda is in the final the result will be executed, the place where x no longer holds 2, and the program adds 3 to an arbitrary integer.
Is there any elegant way to do currying in C ++, ensuring that the variable is captured correctly?
source share