1

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.

  1. [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
    }
    
  2. [&] - [&] 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.

Evg
  • 25,259
  • 5
  • 41
  • 83
harrbanggg
  • 21
  • 1
  • 1
    Does this answer your question? [C++ lambda capture this vs capture by reference](https://stackoverflow.com/questions/33575563/c-lambda-capture-this-vs-capture-by-reference) – Louis Go Jul 30 '20 at 06:15
  • 4
    `[&]` itself doesn't capture data members at all. But when you write `[&]`, `this` is captured implicitly: `[&]` is equivalent to `[&, this]`. – Evg Jul 30 '20 at 06:22
  • @Evg Thanks. then basically if i use member data of the class in lambda expression, can I use [&] or [&, this] or [this] for the same purpose? Thanks. I will choose one of them for coding. – harrbanggg Jul 30 '20 at 06:31
  • 1
    Yes, you can use any one of them. But if you only access data members inside a lambda, `[this]` is all you need. So I suggest using `[this]` to be explicit about your intention. – Evg Jul 30 '20 at 06:34
  • @Evg Thank you for the kind explanation. thanks. – harrbanggg Jul 30 '20 at 06:35
  • 1
    For clarification: `[=]` won't capture data members by value. It will capture `this` implicitly (before C++20), *effectively* capturing data members by reference. – Evg Jul 30 '20 at 06:42

0 Answers0