Looking at various examples with lambda expressions, I came across unexpected behavior for me. In this code, I expect that the variables captured by value will not change inside the lambda. Code execution shows the opposite. Can someone give an explanation. Thanks.
#include <iostream>
#include <functional>
using namespace std;
class Fuu{
public:
Fuu(int v):m_property(v){}
void setProperty(int v ){m_property = v;}
std::function<void(int)> lmbSet {[=](int v){ m_property = v;}};
std::function<void(char *)> lmbGet {[=](char * v){ cout<< v << " "<< m_property << endl;}};
std::function<void()> lmb4Static {[=]{ cout<<"static: "<< s_fild << endl;}};
void call() const {
lmbGet("test") ;
}
static int s_fild ;
int m_property;
};
int Fuu::s_fild = 10;
int main()
{
Fuu obj(3);
obj.call();
obj.setProperty(5);
obj.call();//expect 3
obj.lmbSet(12);
obj.call(); //expect 3
obj.lmb4Static();
Fuu::s_fild = 11;
obj.lmb4Static(); //expect 10
return 0;
}