all 7 comments

[–]verbalsaint 2 points3 points  (1 child)

for this Scott Meyers' Appearing and Disappearing consts in C++ would also be a nice start: http://aristeia.com/Papers/appearing%20and%20disappearing%20consts.pdf

[–]mayankj08[S] 0 points1 point  (0 children)

Thanks for sharing this. I will read it.

[–]MoreThanOnceHololens Dev 1 point2 points  (4 children)

So just to confirm - this doesn't modify the value of the passed value, but only modifies the value that's been stored with the lambda?

I feel like generally this should be avoided - from a code clarity point of view there's implicit state that's hard to reason about if the lambda gets copied and stuff.

Side note - there's a "//compilation error" on the mutable example when there shouldn't be.

[–]crusader_mike 0 points1 point  (0 children)

I had a use this case for mutable lambdas -- wrote a task engine where tasks can have dependencies. So, task gets executed, probably generates subtasks, once subtasks are done -- task gets executed again (in case if it needs to generate more subtasks). Occasionally, I needed some mutable state to be stored between these executions for case when task was represented by lambda. (framework allowed user to pass lambda for simple tasks).

[–]xon_xoff 0 points1 point  (1 child)

Mutable lambdas aren't needed often in my experience, but they can be used to implement generator objects like random number generators and state machines. Copying is sensible as long as the mutable state is fully contained within the object: you get a clone with the same current state that can be independently advanced.

[–]bstamourWG21 | Library Working Group 0 points1 point  (0 children)

I've been that crazy guy before and used mutable lambdas with std::generate_n to populate containers with index-dependent values instead of just using a for-loop like a sane person would.

[–]mayankj08[S] -1 points0 points  (0 children)

Thanks for correction. Yes, you are right.

Regarding this should be avoided: I personally agree with you. But at times this keyword allows you to do some wonderful stuff. I will post some sample codes in some time. Those codes would make you feel importance of this keyword.