C++ lambda copy value in capture-list

2020-03-01 08:12发布

I have a program as below:

int main()
{
    int val = 4;
    auto add = [val](int a)->int{
        val += 2;
        return a+val;
    };
    cout << add(3) << endl;
    cout << val << endl;
    return 0;
}

There's a compiling error in Xcode: Cannot assign to a variable captured by copy in a non-mutable lambda.

My question is: if we choose to use the copy (using "=" or value name), can't this value be assigned a new value or changed?

标签: c++ c++11 lambda
3条回答
甜甜的少女心
2楼-- · 2020-03-01 09:00

The operator () of a lambda is implicitly const unless the lambda is declared mutable - and you can't modify the data members in a const member function. This happens regardless of the type of the capture.

查看更多
不美不萌又怎样
3楼-- · 2020-03-01 09:01

Inside a lambda, captured variables are immutable by default. That doesn't depend on the captured variables or the way they were captured in any way. Rather, the function call operator of the closure type is declared const:

This function call operator or operator template is declared const (9.3.1) if and only if the lambda-expression’s parameter-declaration-clause is not followed by mutable.

Therefore, if you want to make the captured variables modifiable inside the body, just change the lambda to

auto add = [val] (int a) mutable -> int {
    val += 2;
    return a+val;
};

so the const-specifier is removed.

查看更多
Emotional °昔
4楼-- · 2020-03-01 09:15

Just capture it by reference, it will work !!

 auto add = [&val](int a) -> int{ 
       //
}
查看更多
登录 后发表回答