I have this simple code:
#include <iostream>
#include <functional>
class a {
public:
a() {
func = [] {
static int i = 0;
i++;
std::cout << i << std::endl;
};
}
std::function<void()> func;
};
int main()
{
a a1;
a1.func();
a a2;
a2.func();
}
I expected an output like this:
1
1
But instead it was:
1
2
Then I checked the memory addresses of the lambdas in the two instances of a
and they were the same. This means that the lambda is created once and then used in all instances. What I am looking for is to make the constructor create a different lambda every time when it gets called. I turned off the compiler optimizations but there was no effect.
INFO: I am using MSVC.