15

http://coliru.stacked-crooked.com/a/29520ad225ced72d

#include <iostream>

struct S
{
    void f()
    {
        //auto f0 = []     { ++i; }; // error: 'this' was not captured for this lambda function

        auto f1 = [this] { ++i; };    
        auto f2 = [&]    { ++i; };
        auto f3 = [=]    { ++i; };
        f1();
        f2();
        f3();
    }

  int i = 10;  
};

int main()
{
    S s;
    std::cout << "Before " << s.i << std::endl;
    s.f();
    std::cout << "After " << s.i << std::endl;
}

Before 10
After 13

Question: Why does [=] enable modification of member variables in a lambda?

Boann
  • 48,794
  • 16
  • 117
  • 146
q0987
  • 34,938
  • 69
  • 242
  • 387

3 Answers3

19

Question> Why [=] enables modification of member variables in lambda?

Because (see cpp reference) [=] "captures all automatic variables odr-used in the body of the lambda by value and current object by reference if exists"

So [=] capture the current object by reference and can modify i (that is a member of the current object).

max66
  • 65,235
  • 10
  • 71
  • 111
9

If you write in equivalent way, this behavior will be more clear:

auto f3 = [=]    { ++(this->i); };

You not catch i but this, it will be constant but thing that its points to will be editable as in any other pointer.

Yankes
  • 1,958
  • 19
  • 20
6

You can imagine that [=] capture this by value, then using the copied this to access this->i.

a copied this still allows you to access the object this points at.

David Haim
  • 25,446
  • 3
  • 44
  • 78