lambda capture by value mutable doesn't work with const &?

前端 未结 2 1184
悲哀的现实
悲哀的现实 2021-02-07 18:28

Consider the following:

void test( const int &value )
{
    auto testConstRefMutableCopy = [value] () mutable {
        value = 2; // compile error: Cannot a         


        
2条回答
  •  面向向阳花
    2021-02-07 19:08

    mutable allows a lambda to modify copy of a non-const parameter captured by copy, but it does not allow it for const parameters.

    So this code works (and outputs inside 2 outside 1):

    int a = 1;
    [a]() mutable {
        a = 2; // compiles OK
        cout << "inside " << a << "\n";
    }();
    cout << " outside " << a << "\n";
    

    But if we omit mutable, or make a const int, the compiler gives an error.

    In our case, the first lambda gives an error because value is const:

    void test( const int &value )
    

    If we make copyValue const:

    const int valueCopy = value;
    

    then the same error will occur with the second lambda.

提交回复
热议问题