Tuesday Coding Tip 48 — Mutable lambdas

Jakub Neruda
2 min readMay 14, 2024

Tuesday coding tips are short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and LinkedIn.

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 :)

--

--

Jakub Neruda

10+ yrs of C++ experience. I care about Clean code, Software architecture and hobby gamedev.