c++ - Using lambda expressions by value capture -
quick query regarding usage of lambda captures, particularly "by value capture". here code:
class carl{ public: int x; void sayhi(); }; void carl::sayhi(){ auto c1 = [=](){ //capture value std::cout<<&x<<std::endl; x = 10; // access copy? }; c1(); std::cout<<&x<<std::endl; // same address 1 inside lambda std::cout<<x<<std::endl; //prints 10 why???? } int main(int argc, char** argv) { carl x; x.sayhi(); return 0; } my issue that, "by value" captures in lambda supposed affect original? aren't supposed make copy? example, used [=] lambda make copy of variable within class's scope. tried accessing x , directly altered x's original value. tried researching , own words: it's stated accessing variable inside lambda has [=] capture access lambda's local copy.
edit: feeling trying access this pointer captured [=]. therefore, accessing x code accessing this->x same pointer original one. please correct me if i'm wrong.
when accessing non-static class data members inside lambda, capturing this pointer value , accessing class member this->x. means no local copy of x made. modifying actual x in current object.
if fact, if value captured "by value", copy, attempt modify fail. x = 10 not compile if x captured value. need declare lambda mutable if want able modify captured state.
Comments
Post a Comment