Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 171 ยท The Standard Library (STL)

Lambda Expressions

Learn C++ lambdas - syntax, capturing by value, by reference, this and init captures, mutable, generic and template lambdas, lambdas with algorithms, and recursion.

A lambda expression creates an unnamed function object right where you need it. Instead of writing a separate named function just to tell std::sort how to order your data, you write the rule inline: [](int a, int b) { return a > b; }. Lambdas can also capture variables from the surrounding code, so the little function remembers a threshold, a counter or a reference to a container. That combination of "inline" and "remembers context" is why lambdas appear in almost every page of modern C++.

You've already met lambdas briefly in Function Pointers and std::function and in the iterators examples. This lesson covers them completely: the syntax piece by piece, every kind of capture and its lifetime rules, mutable, return types, generic and template lambdas, the "immediately invoked lambda" trick for complex initialization, recursive lambdas with C++23's deducing this, and what the compiler actually generates for you. You'll also learn the bugs experienced developers watch for, especially captured references that outlive their variables.

Lambda syntax

The full shape of a lambda is:

TEXT
[captures] (parameters) specifiers -> return_type { body }

Only the brackets and the body are required. The pieces:

  • [captures]: which outside variables the lambda can use, and how (copy or reference). [] captures nothing.
  • (parameters): like a function's parameter list. You may omit () when there are no parameters ([] { return 42; }), though most code keeps them.
  • specifiers: mutable, constexpr, consteval, static (C++23), noexcept.
  • -> return_type: optional; the compiler deduces the return type from return statements otherwise.

Every lambda expression produces an object of a unique, unnamed closure type. You can't write that type's name, so you store a lambda with auto, pass it to a template parameter, or wrap it in std::function.

C++ Writing and calling lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The -> double in divide matters. Without it, the first return 0; deduces int and the second return a / b; deduces double, and the compiler rejects a lambda whose returns disagree. An explicit return type resolves that, just as it does for functions declared with auto.

Capturing variables

A lambda body can't use the enclosing function's local variables unless it captures them. (Globals, static locals and constexpr values it can use freely.) The capture list says which variables to bring in and how:

Capture Meaning
[x] copy x into the lambda when it's created
[&x] refer to the original x
[=] copy every local the body uses
[&] refer to every local the body uses
[=, &x] copy everything, except refer to x
[&, x] refer to everything, except copy x
[this] access the current object's members (by pointer)
[*this] copy the whole current object (C++17)
[n = expr] init capture: a new member n initialized from any expression (C++14)
[&r = expr] init capture of a reference

The difference between copying and referring shows up as soon as the original variable changes after the lambda is created.

C++ By value versus by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output starts 5 < limit? by value: true, by reference: false: the copy still holds 10, while the reference sees 3. Values captured by copy are snapshots taken when the lambda expression runs, not when the lambda is called.

Prefer naming captures explicitly ([limit], [&total]) over [=] and [&]. Explicit lists document what the lambda depends on and stop you from accidentally capturing something large or short-lived.

mutable and init captures

By default, a lambda's call operator is const, so a value captured by copy can't be modified inside the body. Adding mutable lifts that restriction. The lambda then changes its own copy, and the change persists between calls to that same lambda object, which makes a mutable lambda a tiny stateful object.

Init captures go further: they create a new member with any name and any initializer. That's how you start a counter at a value, store a computed result, or move a move-only object such as a std::unique_ptr into the lambda.

C++ mutable counters and init captures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each call gets its own statement on purpose. In std::println("{} {} {}", next_id(), next_id(), next_id()) the order in which the three arguments are evaluated is unspecified, and GCC happens to evaluate them right to left, printing 102 101 100. Never put several calls to the same stateful lambda in one argument list.

Look at the second line of output: original: 103, copy: 103, original again: 104. Copying next_id copied its counter, and from then on the two lambdas count independently. The same thing happens when you pass a stateful lambda by value to an algorithm: the algorithm may work on a copy, so your original's state doesn't change. If you need the state afterwards, capture a variable by reference instead.

Capturing this inside member functions

Inside a member function, a lambda that uses members must capture this (or the object itself). [this] captures the pointer, so the lambda reads and writes the live object; [*this] copies the whole object, which is safer when the lambda might run after the object is gone, such as in a callback or another thread.

C++20 deprecated the implicit capture of this through [=]. Write [=, this] or [this] to make it visible.

C++ this versus *this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The live callback stores a raw pointer to kitchen. If kitchen were destroyed first, calling live() would be undefined behavior. That's the general rule for every reference-like capture: a lambda that captures by reference (or captures this) must not outlive what it refers to.

Dangling captures: the classic bug

Returning or storing a lambda that captured a local by reference is the most common lambda bug. It compiles silently and fails unpredictably:

C++
#include <functional>

std::function<int()> make_counter() {
    int count = 0;
    return [&count] { return ++count; };   // BUG: count dies when make_counter returns
}

Calling the returned function reads a destroyed variable: undefined behavior. Rules of thumb:

  • If a lambda is used immediately (passed to an algorithm, called in the same scope), capturing by reference is fine and efficient.
  • If a lambda is stored, returned, or sent to another thread, capture by value or with an init capture: [count = 0]() mutable { return ++count; }.
  • Pointers are values too. [p] copies the pointer, not what it points to, so it can dangle as well. Capture a std::shared_ptr by value if shared lifetime is what you need (see shared_ptr and weak_ptr).

Generic and template lambdas

A parameter declared auto makes a generic lambda: the call operator becomes a template, and each call with a new argument type instantiates a new version. It's the lambda form of an abbreviated function template.

When you need to name the type, for example to require both arguments to have the same type or to use the type inside the body, C++20 lets you write an explicit template parameter list: []<typename T>(const std::vector<T>& v) { ... }. You can constrain it with concepts as well.

C++ Generic and template lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The variadic version uses a fold expression to add any number of arguments. Generic lambdas are especially useful with std::visit on a std::variant, as you saw in the utility types lesson.

Immediately invoked lambdas

Sometimes a variable needs several steps to compute, but you'd like it to be const afterwards. A common trick is to define a lambda and call it on the spot. The variable is initialized once, can be const, and the helper logic stays local.

C++ Initializing a const with an immediately invoked lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice the () after the closing brace. Forgetting it is a classic slip: const auto x = [] { ... }; stores the lambda itself, not its result, and the compiler only complains later when you use x as a number.

Recursive lambdas

A lambda can't refer to itself by name, because the variable it's being assigned to isn't fully declared yet. Before C++23 people used std::function (slow, allocates) or passed the lambda to itself as a parameter. C++23's explicit object parameter ("deducing this", see The this Pointer) solves it cleanly: the first parameter this auto self is the lambda, so the body can call self(...).

C++ Recursion with deducing this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The format {:{}} prints an empty string padded to a width given by the next argument, a neat way to indent by depth * 2 spaces. Recursive lambdas with explicit object parameters need an explicit return type when the recursion would otherwise make deduction circular.

What the compiler generates

A lambda is syntactic sugar for a class. The compiler writes a struct with one data member per capture and an operator() holding your body. This is roughly what [factor](int x) { return x * factor; } becomes:

C++
struct __lambda_7 {                 // the real name is unspeakable
    int factor;                     // captured by value
    int operator()(int x) const {   // const unless the lambda is mutable
        return x * factor;
    }
};

That explains every rule you've seen:

  • Captured values are copied at creation because they're constructor arguments.
  • mutable simply removes the const from operator().
  • Two lambdas with identical code still have different types, so a std::vector of lambdas needs std::function (or a captureless lambda converted to a function pointer).
  • A captureless lambda has no data, so it can convert to a plain function pointer; you can force the conversion with unary +, as in +[](int x) { return x; }.
  • Lambdas are as fast as hand-written function objects. Templates such as std::sort see the exact closure type and can inline the call, which is why a lambda comparator usually beats a function pointer. The next lesson, Function Objects and std::function, compares the options in detail.

Lambdas can be evaluated at compile time too: since C++17 they're implicitly constexpr when possible. C++23 also allows static lambdas, [](int x) static { return x * 2; }, for captureless lambdas whose call operator needs no this at all, saving a hidden parameter in tight code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int n = 1; auto f = [n] { return n * 10; }; n = 5; What does f() return?

    A by-value capture copies n when the lambda is created, so the lambda keeps its own n = 1 regardless of later changes.
  2. 2. Why does [count] { ++count; } fail to compile when count is an int captured by value?

    By-value captures are members of the closure, and operator() is const unless the lambda is declared mutable.
  3. 3. auto g = [x = 0]() mutable { return ++x; }; auto h = g; g(); g(); What does h() return now?

    h was copied from g before g was called, so it has its own x starting at 0. Calling h() increments it to 1.
  4. 4. Which lambda is safe to return from a function where int total is a local variable?

    The by-value capture copies total into the closure. The reference captures would dangle once the function returns.
  5. 5. What does const auto x = [] { return 6 * 7; }; store in x?

    Without the trailing () the lambda is not invoked. x is the closure object; write [] { return 6 * 7; }() to store 42.

Summary

  • A lambda [captures](params) -> ret { body } creates an object of a unique closure type; store it with auto, pass it to templates, or wrap it in std::function.
  • [x] copies at creation time, [&x] refers to the original; prefer explicit capture lists over [=] and [&].
  • mutable lets a lambda change its by-value captures; init captures ([n = 0], [p = std::move(ptr)]) create new members, including move-only ones.
  • [this] captures a pointer to the object, [*this] a copy; never let reference captures outlive their variables.
  • auto parameters make generic lambdas; []<typename T>(...) names the type (C++20); this auto self (C++23) enables recursion.
  • Immediately invoked lambdas give you complex initialization of const variables. Lambdas are compiled to small classes with operator(), so they inline as well as hand-written functors.

Next: Function Objects and std::function, where you'll compare lambdas with functors, standard comparators like std::greater, std::function, std::bind_front and std::invoke.