Module 7 · Lambdas and algorithms
7.1Lambdas
Write a small function right where you need it. Capture local variables by value or by reference, change a copy with mutable, write generic lambdas, pass them to functions, and avoid a capture that outlives its variable.
On this page
- Key terms
- In 30 seconds
- Writing a lambda
- Saying the return type with ->
- Captures: using local variables
- Capture by value: [cutoff]
- Capture by reference: [&total]
- Capturing everything: [=] and [&]
- Changing a copy: mutable
- Generic lambdas: auto parameters
- Passing a lambda to a function
- Storing different lambdas: std::function
- Which one should I use?
- Under the hood
- Common pitfalls
- A reference capture that outlives its variable
- Copying a mutable lambda copies its state
- Try it yourself
Key terms
- lambda
- A function you write inline, where you use it, without giving it a name. It creates an object you can call like a function.
- capture list (
[]) - The square brackets that start a lambda.
[x]capturesxby value (the lambda keeps its own copy);[&x]captures it by reference (the lambda refers to the original, but doesn't keep it alive). - trailing return type (
-> T) - A return type written after the parameter list, as in
[](int q) -> double { … }. - closure
- The object a lambda expression creates. It holds the captured variables and can be called.
mutable- A keyword after a lambda's parameter list that lets the body change its by-value captures.
- predicate
- A function that takes a value and returns
trueorfalse, such as is this read good enough. Algorithms use predicates to test elements. - generic lambda
- A lambda with an
autoparameter. It works with any type the body can handle, like a function template. std::function<R(Args...)>- A standard type from
<functional>that can hold any callable with that signature, such asstd::function<bool(int)>.
Many tasks need a small piece of behavior handed to other code: which of two reads comes first, whether a base is G or C, what to do with each score. You could write a named function for each, far from where it’s used. A lambda lets you write that function right where you need it, and lets it use the local variables around it.
In 30 seconds
[](int q) { return q >= 30; }is a function with no name. Store it in anautovariable and call it like any function.- The
[]at the start is the capture list.[x]copies the localxinto the lambda;[&x]refers to the original. - By-value captures are read-only unless you write
mutable. Anautoparameter makes a generic lambda. - A reference capture doesn’t keep its variable alive. A lambda that outlives what it refers to dangles.
Writing a lambda
A lambda has three parts: a capture list in [], a parameter list in (), and a body in {}. The compiler works out the return type from the return statement. Each lambda has its own type with no name you can write, so store it in an auto variable:
#include <print>
auto is_high_quality = [](int quality) { return quality >= 30; };
std::println("{} {}", is_high_quality(35), is_high_quality(12));Output
true false
is_high_quality is a predicate: it takes a value and answers yes or no. Predicates are what the standard algorithms in the next lesson, Iterators and algorithms, take to decide which elements to count, find or keep.
Saying the return type with ->
If the body has several return statements, they must all give the same type. Otherwise the compiler can’t pick one:
auto weight = [](int quality) {
if (quality < 0) {
return 0;
}
return quality / 40.0;
};The compiler rejects this
main.cpp: In lambda function:
main.cpp:5:20: error: inconsistent types ‘int’ and ‘double’ deduced for lambda return type
5 | return quality / 40.0;
| ~~~~~~~~^~~~~~The first return gives an int, the second a double. Write the return type after the parameters with ->, a trailing return type, and every return converts to it:
#include <print>
auto weight = [](int quality) -> double {
if (quality < 0) {
return 0;
}
return quality / 40.0;
};
std::println("{} {}", weight(-5), weight(30));Output
0 0.75
Captures: using local variables
A lambda body can’t use the local variables around it unless it captures them. With an empty [], this fails:
int cutoff = 30;
auto passes = [](int quality) { return quality >= cutoff; };The compiler rejects this
main.cpp: In lambda function:
main.cpp:2:51: error: ‘cutoff’ is not captured
2 | auto passes = [](int quality) { return quality >= cutoff; };
| ^~~~~~
main.cpp:2:16: note: the lambda has no capture-default
2 | auto passes = [](int quality) { return quality >= cutoff; };
| ^
main.cpp:1:5: note: ‘int cutoff’ declared here
1 | int cutoff = 30;
| ^~~~~~Capture by value: [cutoff]
Name the variable in the brackets and the lambda gets its own copy, made when the lambda is created. Changing the original later doesn’t change the copy:
#include <print>
int cutoff = 30;
auto passes = [cutoff](int quality) { return quality >= cutoff; };
cutoff = 10;
std::println("{}", passes(20)); // the lambda still has 30Output
false
Capture by reference: [&total]
Put & before the name and the lambda refers to the original variable instead. It sees later changes, and it can change the variable:
#include <print>
int total = 0;
auto add = [&total](int quality) { total += quality; };
add(30);
add(12);
std::println("{}", total);Output
42
Separate several captures with commas: [cutoff, &total] copies cutoff and refers to total.
Capturing everything: [=] and [&]
A default capture captures every local variable the body uses. [=] copies them all; [&] refers to them all. You can mix one default with named exceptions, like [&, cutoff] (everything by reference except cutoff):
#include <print>
int cutoff = 30;
int total = 0;
auto is_good = [=](int quality) { return quality >= cutoff; };
auto add_if_good = [&](int quality) {
if (is_good(quality)) {
total += quality;
}
};
add_if_good(38);
add_if_good(12);
std::println("{}", total);Output
38
is_good copies cutoff. add_if_good refers to is_good and total: a lambda can capture another lambda like any other variable.
Common pitfallPrefer naming your captures
[=] and [&] are short, but they hide what the lambda depends on. [&] makes every variable a reference, and you can’t see from the lambda which ones might dangle. [=] silently copies anything the body mentions, including a large vector. Writing [cutoff, &total] shows the reader exactly what’s copied and what’s shared.
Changing a copy: mutable
By-value captures are read-only inside the body. Trying to change one is a compile error:
int next_id = 1;
auto label = [next_id] { return next_id++; };The compiler rejects this
main.cpp: In lambda function:
main.cpp:2:33: error: increment of read-only variable ‘next_id’
2 | auto label = [next_id] { return next_id++; };
| ^~~~~~~Write mutable after the parameter list and the lambda may change its own copy. The copy lives inside the lambda, so it keeps its value from one call to the next. The original isn’t touched:
#include <print>
int next_id = 1;
auto label = [next_id]() mutable { return next_id++; };
int first = label();
int second = label();
std::println("{} {}", first, second);
std::println("original: {}", next_id);Output
1 2 original: 1
Since C++23 the empty () before mutable is optional, but you’ll often see it because earlier standards required it.
Generic lambdas: auto parameters
Give a parameter the type auto and the lambda works with any type its body can handle. The compiler writes a separate version for each type you call it with, the same way it does for a function template (see Function templates):
#include <print>
#include <string>
auto twice = [](const auto& value) { return value + value; };
std::println("{}", twice(21));
std::println("{}", twice(0.25));
std::println("{}", twice(std::string("ACGT")));Output
42 0.5 ACGTACGT
const auto& reads the argument without copying it, as const T& does in References.
Passing a lambda to a function
Every lambda has its own unnamed type, so a function that takes “any lambda” is a template. The template parameter Test stands for whatever callable the caller passes: anything you can call with (), such as a function, a lambda, or an object with an operator():
#include <print>
#include <vector>
template <typename Test>
int count_matching(const std::vector<int>& qualities, Test test) {
int count = 0;
for (int q : qualities) {
if (test(q)) {
++count;
}
}
return count;
}
int main() {
std::vector<int> qualities = {12, 38, 40, 9, 33};
int cutoff = 30;
auto good = [cutoff](int q) { return q >= cutoff; };
std::println("{}", count_matching(qualities, good));
std::println("{}", count_matching(qualities, [](int q) { return q < 10; }));
}Output
3 1
The compiler sees the exact lambda type, so with optimization on it can usually put the body straight into count_matching (inline it) and skip the call.
Storing different lambdas: std::function
A template parameter can’t help when you need one variable, or one vector, to hold different lambdas. Each lambda has a different type. std::function<bool(int)>, from <functional>, can hold any callable that takes an int and returns a bool:
#include <functional>
#include <print>
#include <string>
#include <vector>
struct Rule {
std::string name;
std::function<bool(int)> test;
};
int main() {
int cutoff = 30;
std::vector<Rule> rules = {
{"high", [cutoff](int q) { return q >= cutoff; }},
{"even", [](int q) { return q % 2 == 0; }},
};
for (const auto& rule : rules) {
std::println("{}: {}", rule.name, rule.test(38));
}
}Output
high: true even: true
Rule is a struct, from Structs and classes. Because the type in std::function<…> is the same for every rule, all the rules fit in one vector.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
No captures ([]) | The lambda needs only its parameters. | Nothing to copy or to dangle. | [](int q) { return q < 10; } |
Capture by value ([x]) | Small values the lambda reads, or any lambda that outlives the current scope. | The lambda has its own copy, so it can’t dangle (unless the copy is itself a pointer or a view such as std::string_view). | [cutoff](int q) { return q >= cutoff; } |
Capture by reference ([&x]) | The lambda changes a local, or reads a big object, and is used before that variable goes away. | No copy, and changes are visible outside. | [&total](int q) { total += q; } |
| Template parameter | A function takes a lambda and calls it. | No extra cost; the compiler sees the exact lambda. | template <typename F> void f(F fn) |
std::function | You store lambdas of different types in one variable or container. | One type for every callable with that signature. | std::function<bool(int)> test = …; |
Rule of thumb: name each capture. Capture by reference only when the lambda is used right away; if it’s stored or returned, capture by value.
Under the hood
A lambda expression creates an object, called a closure. The compiler writes a class for it, a function object like those in Operators and comparisons: one member for each by-value capture, and an operator() that holds the body. These two do the same thing:
#include <print>
struct PassesCutoff {
int cutoff;
bool operator()(int quality) const { return quality >= cutoff; }
};
int main() {
int cutoff = 30;
PassesCutoff by_hand{cutoff};
auto lambda = [cutoff](int quality) { return quality >= cutoff; };
std::println("{} {}", by_hand(35), lambda(35));
}Output
true true
The const on operator() is why by-value captures are read-only: a const member function can’t change the object’s members. mutable removes that const.
The standard leaves a closure’s size and layout to the compiler. With GCC on this platform, a closure with no captures is an empty object of 1 byte, each by-value capture adds the variable’s size, and a reference capture is stored as an address, 8 bytes. A std::function is bigger, 32 bytes with GCC’s standard library:
#include <functional>
#include <print>
int cutoff = 30;
double weight = 1.5;
int count = 0;
auto none = [](int q) { return q >= 30; };
auto two_values = [cutoff, weight](int q) { return q * weight >= cutoff; };
auto one_reference = [&count] { ++count; };
std::println("{} {} {}", sizeof(none), sizeof(two_values),
sizeof(one_reference));
std::println("{}", sizeof(std::function<bool(int)>));Output
1 16 8 32
two_values is 16 bytes, not 12: on this platform a double must start at an address that’s a multiple of 8, so GCC leaves 4 unused bytes next to the int (Module 9 covers this padding). Here’s a closure with one capture of each kind:
#include <print>
int count = 0;
int cutoff = 30;
auto tally = [cutoff, &count](int q) {
if (q >= cutoff) {
++count;
}
};
tally(38);
std::println("{}", count);Output
1
A std::function has to hold closures of any size, so it may copy a large one to the heap, and every call goes through a pointer to the right code. That costs a little on each call. Prefer a template parameter where you can.
Common pitfalls
A reference capture that outlives its variable
A capture by reference doesn’t keep the variable alive. Here make_counter returns a lambda, wrapped in a std::function, that refers to count. But count is a local variable, destroyed when make_counter returns. Calling the lambda afterwards uses a variable that no longer exists, which is undefined behavior. Neither compiler warns; AddressSanitizer catches it here when the program runs:
#include <functional>
#include <print>
std::function<int()> make_counter() {
int count = 0;
return [&count] { return ++count; };
}
int main() {
auto next = make_counter();
std::println("{}", next());
}This fails when it runs
ERROR: AddressSanitizer: stack-use-after-return on address 0x…
READ of size 4 at 0x… thread T0
#0 operator() main.cpp:6
… 4 frames inside the standard library
#5 main main.cpp:11
Address 0x… is located in stack of thread T0 at offset 48 in frame
#0 make_counter() main.cpp:4
This frame has 2 object(s):
[48, 52) 'count' (line 5) <== Memory access at offset 48 is inside this variable
[64, 72) '<unknown>'
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-use-after-return main.cpp:6 in operator()The fix is to capture by value. The closure then owns its own count, so it lives as long as the closure does; mutable lets it change:
#include <functional>
#include <print>
std::function<int()> make_counter() {
int count = 0;
return [count]() mutable { return ++count; };
}
int main() {
auto next = make_counter();
int first = next();
int second = next();
std::println("{} {}", first, second);
}Output
1 2
If make_counter returns the lambda directly, with an auto return type, Clang spots this simple case and warns that it returns the address of a local variable. GCC doesn’t. Once the lambda passes through a std::function, a vector or a struct, neither compiler can see the problem, so don’t count on the warning.
Undefined behaviorWatch lambdas that leave the scope
The same bug happens whenever you call a stored lambda after the variables it refers to are gone. Any lambda that’s returned or stored should capture by value. ASan names the kind of bug: stack-use-after-return here, stack-use-after-scope when a block ended, heap-use-after-free when the variable was on the heap.
Copying a mutable lambda copies its state
A closure is an object, and passing it by value copies it, captures and all. A mutable lambda passed by value counts in the copy, not in the original:
#include <print>
template <typename F>
void call_twice(F f) {
f();
f();
}
int main() {
int calls = 0;
auto counter = [calls]() mutable {
++calls;
std::println("call {}", calls);
};
call_twice(counter);
counter();
}Output
call 1 call 2 call 1
The last line prints call 1 because call_twice worked on a copy. If you want one shared count, keep the count outside the lambda and capture it by reference, [&calls], or have the function take F& f.
Try it yourself
Try it yourself
This program should count the reads with a quality below cutoff, but it prints 0 reads below 30. Fix the capture list so it prints the right count.
#include <print>
#include <vector>
int main() {
std::vector<int> qualities = {12, 38, 40, 9, 33};
int cutoff = 30;
int low_count = 0;
auto record = [cutoff, low_count](int q) mutable {
if (q < cutoff) {
++low_count;
}
};
for (int q : qualities) {
record(q);
}
std::println("{} reads below {}", low_count, cutoff);
}Expected output
2 reads below 30
Show a hint
low_count is captured by value, so the lambda changes its own copy and the program prints the original 0. Capture it by reference instead.
Show a solution
#include <print>
#include <vector>
int main() {
std::vector<int> qualities = {12, 38, 40, 9, 33};
int cutoff = 30;
int low_count = 0;
auto record = [cutoff, &low_count](int q) {
if (q < cutoff) {
++low_count;
}
};
for (int q : qualities) {
record(q);
}
std::println("{} reads below {}", low_count, cutoff);
}[cutoff, &low_count] copies cutoff, which the lambda only reads, and refers to the real low_count, so each ++low_count changes the variable that's printed. mutable is no longer needed, because the lambda doesn't change any by-value capture.
Saved in this browser only.