A lambda is a small unnamed function that you can write where it is used. It has three parts. There is the capture list in the square brackets, there is the parameter list in the parentheses, and there is the body. The capture list is the part that makes a lambda different from an ordinary function, because it says which of the variables from the surrounding scope the lambda may use.
The previous lesson in this module covered "What Do auto and range-based for Simplify?", and the next lesson in this module is about "What Do Structured Bindings, optional and variant Add?".
The shape of a lambda
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> weights = {4, 30, 12, 8};
std::sort(weights.begin(), weights.end(),
[](int left, int right) { return left > right; });
for (int weight : weights) {
std::cout << weight << ' ';
}
std::cout << '\n';
return 0;
}The output shows the vector sorted in the descending order.
30 12 8 4And with an empty capture list the lambda sees nothing from the surrounding scope. That is the safest default, and it is why the lambda above compiles without any qualification, because the parameter types are written out.
Capturing by value and by reference
The capture list says which outside variables the lambda may use, and how.
the capture list what it does
----------------- -----------------------------------------------
[] captures nothing
= captures everything used, by value
& captures everything used, by reference
name captures this one, by value
&name captures this one, by reference
this captures the pointer to the enclosing object
#include <iostream>
#include <vector>
int main() {
int threshold = 15;
std::vector<int> weights = {4, 30, 12, 8};
auto heavy_by_value = [threshold](int weight) {
return weight > threshold;
};
auto heavy_by_reference = [&threshold](int weight) {
return weight > threshold;
};
threshold = 5;
std::cout << "by value: " << heavy_by_value(12) << '\n';
std::cout << "by reference: " << heavy_by_reference(12) << '\n';
return 0;
}The output shows the difference. The by-value lambda kept the old threshold of 15 and returned false, while the by-reference lambda saw the new value of 5 and returned true.
by value: 0
by reference: 1And the general rule is simple. You capture by reference when the lambda should see the later changes, and you capture by value when it should not.
Returning from a lambda
A lambda returns whatever its body returns, and the compiler deduces the type. When the branches return different types, you need an explicit return type.
#include <iostream>
#include <string>
#include <vector>
int main() {
auto describe = [](int weight) -> std::string {
return weight > 20 ? "heavy" : "light";
};
std::cout << describe(30) << '\n';
std::cout << describe(4) << '\n';
// With an explicit return type, different branches are allowed.
auto mixed = [](int weight) -> double {
if (weight > 20) {
return 1; // converts to double
}
return 0.5;
};
std::cout << mixed(30) << '\n';
return 0;
}The output shows the lambda returning a string and then a double.
heavy
light
1And the -> std::string and the -> double are optional when the types agree, and they are necessary when they do not.
Capturing this in a member function
Inside a member function, the this captures the enclosing object, so the lambda can call its member functions.
#include <iostream>
#include <string>
#include <vector>
class Warehouse {
public:
explicit Warehouse(std::vector<std::string> parcels)
: parcels_(std::move(parcels)) {}
void report() const {
auto describe = [this]() {
std::cout << "holds " << parcels_.size() << " parcels\n";
};
describe();
}
private:
std::vector<std::string> parcels_;
};
int main() {
Warehouse warehouse({"p-001", "p-002"});
warehouse.report();
return 0;
}The output shows the lambda reaching the member variable.
holds 2 parcelsAnd the explicit [this] capture is the default in C++20, but writing it in C++17 makes the intent obvious and it silences a warning that some of the compilers emit.
Lambdas and function pointers
A lambda with no capture can be converted to a function pointer, and that is what lets you pass one to a C-style API.
#include <algorithm>
#include <iostream>
#include <vector>
int apply_discount(int price) {
return price * 9 / 10;
}
int main() {
std::vector<int> prices = {100, 200};
auto lambda = [](int price) { return price * 9 / 10; };
int (*function_pointer)(int) = lambda;
std::cout << "lambda: " << lambda(100) << '\n';
std::cout << "pointer: " << function_pointer(100) << '\n';
std::cout << "function: " << apply_discount(100) << '\n';
return 0;
}The output shows all three of them producing the same result.
lambda: 90
pointer: 90
function: 90And a lambda that captures something cannot be converted to a function pointer, because a function pointer has nowhere to put the captured state.
When to use a lambda
Lambdas are the right tool when the behaviour is short, when it is local, and when it is used in one place. That means sorting with a custom comparator, checking a predicate and transforming a range.
When the behaviour is long, when it is reused in many places, or when it needs a state of its own, then a named class is better.
Common lambda mistakes
- Capturing a local by reference and then outliving it. The lambda then refers to a destroyed object, so you capture by value instead.
- Forgetting that a by-value capture copies, so changing the captured copy inside the lambda does not change the original.
- Capturing the enclosing object implicitly in a lambda that outlives it, which is the same dangling problem one level up.
- Expecting a lambda to be mutable. By default the captured objects are const inside the lambda, and you add the mutable to change that.
Quick reference
- A lambda is
[capture list](parameters) { body }. - You capture nothing with the empty brackets, everything by value with the equals sign, and everything by reference with the ampersand.
- You capture by reference to see the later changes, and by value to insulate the lambda.
- The return type is deduced, but it can be written with the arrow and the type.
- A captureless lambda converts to a function pointer, and one with the captures does not.
- You use a named class when the behaviour is long or it is reused.
Try it yourself: write a lambda that takes a weight and a threshold and returns whether the weight exceeds it, capturing the threshold by value and then by reference, and call both of them after you change the threshold. Next, use a lambda with the this inside a class method to report a member. Finally, pass a captureless lambda to a function that expects a function pointer.