Compiler Error C3491

Visual Studio 2015
 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at Compiler Error C3491.

var': a by-value capture cannot be modified in a non-mutable lambda

A non-mutable lambda expression cannot modify the value of a variable that is captured by value.

To correct this error

  • Declare your lambda expression with the mutable keyword, or

  • Pass the variable by reference to the capture list of the lambda expression.

The following example generates C3491 because the body of a non-mutable lambda expression modifies the capture variable m:

// C3491a.cpp  
  
int main()  
{  
   int m = 55;  
   [m](int n) { m = n; }(99); // C3491  
}  

The following example resolves C3491 by declaring the lambda expression with the mutable keyword:

// C3491b.cpp  
  
int main()  
{  
   int m = 55;  
   [m](int n) mutable { m = n; }(99);  
}  

Lambda Expressions

Show: