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.
static int istatic, if you do not want shared state ? If you want to store per-instance variables, make them a member ofclass a, and capture that member in the lambda.a::funccan be avoid(*)()function pointer, and it will always be the same function pointer. That is the automatic result from your requirement that it doesn't capture. So you really have two incompatible requirements here. Which one is real?this) that is accessible to aWNDPROC. Had you tried asking about that, something like this Q&A would have popped up.