2

When lambda expression's captures by reference( [&] ) marking mutable or not it still changing the value. But capturing by value needs mutable to change the object.

int main(){
   int x = 10;
   auto ByValue = [x](){ --x; }; // error: decrement of read-only variable 'x'
   auto ByRef   = [&x](){ --x; }; //No Error
   auto ByValM  = [x]()mutable{ --x; }; // No error
   auto ByRefM  = [&x]()mutable{ --x; }; // No error
}

link to the demo

Why [&x](){ --x; }; is able to change the variable x? Is it that capturing by reference marks the lambda expression mutable implicitly?

TheScore
  • 329
  • 3
  • 14
  • 3
    _"...`mutable`: allows body to modify the objects __captured by copy__, and to call their non-const member functions..."_ https://en.cppreference.com/w/cpp/language/lambda Capture by reference is capture by reference. No need for `mutable` is changing the value of the reference it not changing the value of the lambda just the referred to object, the lambda can still be const. – Richard Critten Apr 27 '21 at 18:15
  • By reference is mutable, unless it's a const object or const reference. Only capture by copy is const by default – JHBonarius Apr 27 '21 at 18:17
  • Thank you guys. I found this answer https://stackoverflow.com/q/5501959/12582758 it solves my question. – TheScore Apr 27 '21 at 18:23
  • @RichardCritten Perfect makes sense now. Thank you. – TheScore Apr 27 '21 at 18:24
  • 1
    @Yelp since it solved your problem I added it as duplicate for future readers – Guillaume Racicot Apr 27 '21 at 18:34

0 Answers0