C ++ 11: Volatile lambda doesn't seem to modify a variable?

I have a quick test below:

#include<iostream>
using namespace std;
int main(){
    int i=2;
    auto f=[=]()mutable{++i;};
    f();
    f();
    cout<<i<<endl;
    return 0;
}

      

But the result still prints "2". Why am I not modified inside a volatile lambda? I am using clang -std = c ++ 1z.

Thank!

+3


source to share


3 answers


int i=2;
auto f=[=]()mutable{++i;};
f();
f();
std::cout<<i<<std::endl;

      

this prints 2.

int i=2;
auto f=[&](){++i;};
f();
f();
std::cout<<i<<std::endl;

      

this prints 4.

int i=2;
auto f=[=]()mutable{++i; std::cout << i << std::endl;};
f();
f();
std::cout<<i<<std::endl;

      

this prints 3 4 2.



=

copies the collected data to a lambda.

If copiesmutable

can be modified .

&

links the committed data to the lambda.

Changing links through links is legal.

[=]

is the same as, and [i]

, [&]

in this context, is the same as [&i]

(you can explicitly map the captures, or let them capture implicitly without listing any and using =

or &

).

+7


source


You are using [=]

for your capture, which means the lambda gets a copy i

. This copy is independent of i

c main

.



What you need to do is grab the link [&]

to apply the changes to i

in main

.

+9


source


[=]

means you are writing i

by value. Even a mutable lambda can change it, but it is just a copy inside the lambda, then any modification on it will have nothing to do with the original variable.

You may want capture-by-reference and then mutable

not needed anymore. eg.

auto f = [&i]() {++i;};

      

+2


source







All Articles