C++ lambda copy value in capture-list

后端 未结 3 734
慢半拍i
慢半拍i 2021-01-04 03:05

I have a program as below:

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


        
3条回答
  •  一个人的身影
    2021-01-04 03:22

    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.

提交回复
热议问题