skip to content

What class does a C++ compiler generate for a lambda expression, and why must a lambda be mutable to modify a by-copy capture?

level: middleimportance: must knowfreq 65%

answer

  1. unnamed class, one per lambda
  2. captures become data members
  3. operator() is const by default
  4. each copy carries its own state

basics

~20 s

Each lambda expression has its own unnamed closure class: by-copy captures become data members and the body becomes operator(). That operator() is const unless the lambda is declared mutable, so the body cannot change its copied members without mutable.

solid answer

~40 s

A lambda expression's type is a **closure type**: a unique, unnamed class, different for every lambda expression even when two are spelled identically. Each by-copy capture becomes an unnamed non-static data member, and the body becomes a public inline `operator()`. That call operator is declared `const` unless the lambda says `mutable`, so a body that assigns to or increments a copied capture fails to compile: Clang reports `cannot assign to a variable captured by copy in a non-mutable lambda`. With `mutable`, the body changes the **closure's member**, never the original variable, and every copy of the closure carries its own copy of that state. A lambda with an empty capture list also gets a conversion to an ordinary function pointer, which any other lambda lacks.

code

cpp · 17 lines
cpp
#include <cstdio>
#include <type_traits>

int main() {
  int clicks = 0;
  auto counter = [clicks]() mutable { return ++clicks; };  // edits its own member
  auto copy = counter;          // copies the closure, member included
  counter();
  counter();
  std::printf("counter=%d copy=%d outer=%d\n", counter(), copy(), clicks);

  auto a = [] { return 1; };
  auto b = [] { return 1; };
  static_assert(!std::is_same_v<decltype(a), decltype(b)>);  // two distinct closure types
  int (*fp)() = a;              // captureless: converts to a function pointer
  std::printf("fp()=%d sizeof(counter)=%zu\n", fp(), sizeof counter);
}

go deeper

for a junior

Recall that a lambda is an object of an unnamed class and that changing a copied capture needs mutable.

for a middle

Explain the closure type: captures as members, the const call operator, a unique type per expression, and the function pointer conversion for captureless lambdas.

for a senior

Use the model to predict behaviour of copies: algorithms copy function objects, so a mutable counter inside one may not report what the caller expects.

for a principal

Weigh stateful mutable lambdas against explicit function objects or reference captures when a team's code passes callbacks through layers that copy them.

## The closure type The standard describes a lambda expression in terms of a class it never names. Evaluating the expression creates a **closure object** whose type, the **closure type**, is a unique, unnamed, non-union class. Unique means unique per lambda expression: two lambdas written character for character the same still have two different types, which is why you hold one in `auto`, pass it to a template, or erase its type in a wrapper. What the class contains: - one unnamed non-static **data member** for each entity captured by copy, in an unspecified order, initialized when the lambda expression is evaluated; - a public inline **function call operator** whose parameters and return type are the lambda's own; for a generic lambda it is a member function template; - a defaulted copy constructor and move constructor, and, when the lambda has captures, a **deleted copy assignment operator**; - for a lambda with an empty capture list and no explicit object parameter, a **conversion function** (a conversion function template, for a generic lambda) to a plain pointer to function. For the counter in the code example, the model is roughly this hand-written class (the real one has no name you can spell): ```cpp class CounterClosure { // a sketch, not compiler output int clicks; // the by-copy capture public: explicit CounterClosure(int c) : clicks(c) {} int operator()() { return ++clicks; } // no const, because of mutable }; ``` Without `mutable`, that `operator()` would be declared `const`. An implementation may change the size, alignment, trivial copyability and standard-layout status of the closure from what this model suggests. The code example printed `sizeof(counter)=4` with Apple clang 21: one `int` member, but that is that compiler's layout, not a guarantee. ## Why the call operator is const The call operator of a lambda is declared `const` unless the parameter list is followed by `mutable` (or uses an explicit object parameter, a form added in C++23). Inside a `const` member function every data member is read-only, so a body that writes a by-copy capture is ill-formed. The second code example shows Clang's diagnostic: `error: cannot assign to a variable captured by copy in a non-mutable lambda` The usual rationale is that calling the same closure twice should normally give the same result. A lambda that silently changed its own state on every call would surprise callers that copy it, and many standard algorithms copy the function objects they are given. ## What mutable changes, and what it does not 1. `mutable` removes the `const` from the call operator, so the body can modify its by-copy members. 2. It changes the **closure's copy only**. In the example, `outer=0` shows that the original `clicks` in `main` never moved. 3. Each copy of the closure has its own members. `copy` was made before `counter` was called, so `counter()` reaches 3 while `copy()` returns 1. 4. `mutable` has no effect on by-reference captures: a body may always write through a reference capture, because the closure does not own the referenced variable. 5. A `mutable` closure can be called only through a non-const object or reference. Passing it somewhere that holds it as `const` fails to compile. ## The function pointer conversion A lambda with **no lambda-capture** converts implicitly to a function pointer with the same signature, so it can be handed to a C API that takes a callback pointer. The condition is the capture list, not what is actually used: `[&](int x) { return x * 2; }` captures nothing, yet Clang rejects converting it to `int (*)(int)` because it has a capture default. A capturing lambda has state, and a bare function pointer has nowhere to keep it. ## Mistakes interviewers listen for - Believing two identical lambdas share a type, or that the type can be written down. - Believing `mutable` lets the body change the original variable. - Believing copies of a `mutable` closure share one counter. - Making a lambda `mutable` to silence an error when the real intent was a by-reference capture, or the reverse. - Expecting any lambda to convert to a function pointer; only one with an empty capture list does. ## How to answer Describe the unnamed class: captures as members, the body as `operator()`, a new type per expression. Then explain that `operator()` is `const` by default, that `mutable` lifts it for the closure's own copies only, and that each closure copy has independent state.

  • Why does assigning one std::optional of a capturing lambda's type to another fail to compile?
    A closure type with captures has a deleted copy assignment operator, so `std::optional` of that type has its copy assignment implicitly deleted as well; Clang says the optional cannot be assigned because its copy assignment operator is implicitly deleted. Construction still works, because the closure's copy and move constructors are defaulted, and `emplace` replaces the value without assigning.
  • Does mutable affect captures taken by reference?
    No. A by-reference capture never belongs to the closure, so the body may write through it even when the call operator is `const`. `mutable` only lets the body modify the closure's own by-copy members, and those changes never reach the original variable.

A mutable lambda is like a tally counter handed out at a door: each copy of the counter clicks on its own, and photocopying a counter gives you a second counter with whatever number it showed at that moment, not a window onto the first.

  • Two lambdas with identical text have the same type.
  • mutable lets the body change the original variable in the enclosing function.
  • Copies of a mutable closure share a single captured counter.
  • Any lambda that captures nothing it uses converts to a function pointer, even [&].
  • A by-copy capture is const because the original variable becomes const.