Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?

Tags:

c++

c++11

lambda

Short example:

#include <iostream>  int main() {     int n;     [&](){n = 10;}();             // OK     [=]() mutable {n = 20;}();    // OK     // [=](){n = 10;}();          // Error: a by-value capture cannot be modified in a non-mutable lambda     std::cout << n << "\n";       // "10" } 

The question: Why do we need the mutable keyword? It's quite different from traditional parameter passing to named functions. What's the rationale behind?

I was under the impression that the whole point of capture-by-value is to allow the user to change the temporary -- otherwise I'm almost always better off using capture-by-reference, aren't I?

Any enlightenments?

(I'm using MSVC2010 by the way. AFAIK this should be standard)

like image 843
kizzx2 Avatar asked Mar 31 '11 15:03

kizzx2


People also ask

What is mutable in lambda?

The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes.

Does lambda capture reference by value?

Lambdas always capture objects, and they can do so by value or by reference.

What is the use of mutable keyword in C++?

Mutable Data Members (C++)This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable , then it is legal to assign a value to this data member from a const member function.

What is lambda function in C ++ 11?

C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f . For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form: void func3(std::vector<int>& v) { std::for_each(v.


1 Answers

It requires mutable because by default, a function object should produce the same result every time it's called. This is the difference between an object orientated function and a function using a global variable, effectively.

like image 75
Puppy Avatar answered Sep 30 '22 05:09

Puppy