Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can [=] be used to modify member variables in a lambda?

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?

like image 681
q0987 Avatar asked Mar 19 '17 01:03

q0987


2 Answers

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).

like image 111
max66 Avatar answered Oct 04 '22 00:10

max66


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.

like image 38
Yankes Avatar answered Oct 03 '22 23:10

Yankes