Why do we need to take the link to the link in lambda?

Consider this:

class TestLambda {
public:
    std::vector<char> data;
};

void test_lambda(TestLambda& obj) {
    [=]() mutable {
        obj.data.push_back(0x01);
    }();
}

int main() {
    TestLambda tst;
    tst.data.push_back(0x99);
    test_lambda(tst);

    // tst.data is unchanged at this point

    return 0;
}

After the call, test_lambdaI expected to see the change in tst.data, but it is not. To see the changes, I had to create a lambda, again passing the link obj, i.e. [&obj]().

Why do we need this? I mean, link again?

objis already a link. Then lambdacaptures obj, copying it. So, objinside is lambdanot a link? Why?

Can someone explain this to me? Thanks.

+4
source share
3 answers

"" . , , , :

auto my_inner_variable = my_outer_reference;
auto my_inner_other_variable = my_outer_other_variable;

, "" , , :

auto& my_inner_variable = my_outer_reference;
auto& my_inner_other_variable = my_outer_other_variable; // if we instructed to capture everything by reference
+5

§5.1.2/p15 - [expr.prim.lambda] (Emphasis Mine):

, , - = / . , , . . - , . [: , . - end note] .

, :

void test_lambda(TestLambda& obj) {
    [=]() mutable {
        obj.data.push_back(0x01);
    }();
}

obj , . , , [=] .

+3

test_lambda -. test_lambda obj tst . -, . - obj obj, test_lambda. :

void test_lambda(TestLambda& obj) {
   obj.data.push_back(0x01);
}

, , ,

void test_lambda(TestLambda& obj) {
    [=]() mutable {
        objCopy.data.push_back(0x01);
    }();
}

objCopy lambda.

0

Source: https://habr.com/ru/post/1616208/


All Articles