Did you know? If you capture by copy in a C++ lambda, the captured value is read-only. That is not a problem when capturing by reference, which allows for modification of the referenced value.
#include <print>
int main()
{
auto&& i = 0;
[&i] // <-- capture by reference
{ i++; } ();
std::println("{}", i); // 1
[i] // <-- capture by copy
{
// error: cannot assign to a variable captured
// by copy in a non-mutable lambda
i++;
} ();
}
One possible workaround is to create a static variable inside the lambda and initialize it with the original by-copy captured value. Such solution is certainly reasonable when only one variable is captured.
#include <print>
int main()
{
auto&& i = 0;
auto&& l = [i] {
static int j = i;
return ++j;
};
l(); l();
std::println("{} | {}", i, l()); // 0 | 3
}
If you capture multiple variables (perhaps though = wildcard), such static declarations could get lengthy. But worry not! You can declare the lambda as mutable, so you can edit all values captured by copy.
#include <print>
int main()
{
auto&& i = 0;
auto&& l = [i] mutable { return ++i; };
l(); l();
std::println("{} | {}", i, l()); // 0 | 3
}
That said, I’d be surprised if there was a truly valid use case for this feature. If you can think of any, please share your thoughts in the comments :)