Mutable lambdas in C++
06 Aug 2017This post is in continuation to Lambdas in C++.
Till now we covered basics of functors and lambdas in C++. We will cover Mutable lambdas in this post.
Mutable Lambdas
Object captured in lambda are immutable by default. This is because operator()
of the generated functor (compiler generates functional object for lambdas) is const
by default. Consider below C++ code:
#include<iostream>
int main(){
int a=10;
auto lam = [a](){a;};
lam();
return 0;
}
Assembly code for lambda lam
generated by gcc 4.9.4 is:
main::{lambda()#1}::operator()() const:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
pop rbp
ret
As you can see that const
keyword is present in generated functor of lambda main::{lambda()#1}::operator()() const
. This const
prevent us from modifying objects in lambda captured by value.
int a=10;
auto lam = [a](){a++;}; //Compilation error
Using mutable
keyword allows us to mutate objects captured by value too.
int a=10;
auto lam = [a]() mutable {a++;};
If we see the assembly code for same code the generated functor after adding mutable keyword looks like:
main::{lambda()#1}::operator()()
We can clearly see that const
is no longer present now. So adding mutable
keyword makes operator()
non-const
.
In general lambda declaration mutable
keyword comes before return-type
auto func = [a]() mutable -> int {++a; std::cout << a; return a;};
That’s it for mutable lambdas. I think we covered basics of lambdas. We will start with R-value reference from next blog post.
Till then Sayonara.