Consider the following:
void test( const int &value )
{
auto testConstRefMutableCopy = [value] () mutable {
value = 2; // compile error: Cannot a
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.