Search code examples
c++c++11lambdamutable

C++11: The mutable lambda doesn't seem to change the variable?


I've got 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 it still prints "2". Why i is not modified inside a mutable lambda? I'm using clang --std=c++1z.

Thanks!


Solution

  • 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 captured data into the lambda.

    If mutable the copies can be modified.

    & references captured data in the lambda.

    Modifying things through references is legal.

    [=] is the same as [i], and [&] is the same as [&i] in this context (you can explicitly list captures, or let them be captured implicitly by listing none and using = or &).