gotchacppCritical
Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?
Viewed 0 times
capturewhyformutabledoesrequirevaluelambdakeyworddefault
Problem
Short example:
The question: Why do we need the
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)
#include
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)
Solution
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.Context
Stack Overflow Q#5501959, score: 282
Revisions (0)
No revisions yet.