3 ms·
> Variables are default mutable and you have to make them const Except for the captured variables in a lambda which are const unless you use the mutable keywor
by JTyQZSnP3cQGa8B 2y ago
> Variables are default mutable and you have to make them const
Except for the captured variables in a lambda which are const unless you use the mutable keyword. Not a bad idea though.
- Maxatar 2y agoAnd that's only true if you capture by value. If you capture by reference they remain mutable.
- chombier 2y agoI think this is because `mutable` qualifies the call operator of the lambda (like a reverse const qualifier) so by-value captures are effectively const during the call unless the lambda is marked `mutable`. References themselves are always const, but the referenced object may be modified through the reference depending on its constness even though the lambda is not `mutable`. Is there a way to force capture by const-reference by the way?
- gpderetta 2y agoint main() { int x = 0; [&x] { x= 1;}(); // works [&x=std::as_const(x)] { x= 1;}(); // error: assignment of read-only reference 'x' } Not very pretty, but it works.