On 09.08.2019 18:30,
porp...@gmail.com wrote:
> Hi,
>
> Could you please explain me why capturing variables by value in a lambda is immutable by default ?
>
> [=] () { ++ outsideVar; } (); // compilation error
It's the only place that C++ got `const` practically correct, as the
default.
It couldn't very well do that for the machinery inherited from C, and
Bjarne started designing classes around 1980, before the benefits and
desirability of `const` was realized (at the time his preferred keyword
was `readonly`, as I recall: the concept hadn't even crystallized).
But lambda did not enter the language until C++11, that is, in 2011.
`const` is useful because it /constrains/ what can possibly happen.
That facilities understanding of code, writing correct code in the first
place, and when the compiler knows that `outsideVar` won't be changing
over the lifetime of the lambda it can outfit the lambda with just a
reference instead of doing a possibly costly copying of full value.
> I'm aware of "mutable" keyword in this scenario.
Yep.
I don't wish it was like that for ordinary variables because `mutable`
is too long a keyword for the not uncommon case where one wants a
variable to be actually variable...
But something like `var`, that would have been nice.
Happily we can now write efficient loops with `const` loop variable:
for( const int i: up_to( n ) ) ...
... with a suitable simple definition of an `up_to` function, which with
the C++20 ranges library might be a simple alias (I'm not sure though).
Alas, re the ordinary variables, C legacy.
Cheers!,
- Alf