Could you please tell me the difference between capturing of [this] and [&]? (In case of a lambda is defined inside a member function of the class)
As I understood, there is no difference between both of them.
- [this]-- [this]means capturing all the member data of the class. Capturing- [this]means capturing the address of the object.- #include <iostream> class Foo { int x; public: Foo() : x(10) {} void bar() { // Increment x every time we are called auto lam = [this](){ return ++x; }; std::cout << lam() << std::endl; } }; int main() { Foo foo; foo.bar(); // Outputs 11 foo.bar(); // Outputs 12 }
- [&]-- [&]means capture all variables by reference all variables mean local variable, global variable and member data of the class.- class Foo { int x; public: Foo() : x(10) {} void bar() { // Increment x every time we are called auto lam = [&](){ return ++x; }; std::cout << lam() << std::endl; } }; int main() { Foo foo; foo.bar(); // Outputs 11 foo.bar(); // Outputs 12 }
I believe that there is no difference between [this] and [&]. Because by both capturing data is captured by reference. so the data can be changed.
- [this]captures address of the data (reference value)
- [&]captures all data by reference
Is my understanding is wrong? Please give me some advice.
 
    