1std::vector<int> v{3, 8, 1, 9};2int limit = 5;3auto big = [limit](int x) {auto big = [&limit](int x) {4 return x > limit;5};6limit = 100;7auto n = std::count_if(8 v.begin(), v.end(), big);main()'s variablesv[0]3v[1]8v[2]1v[3]9limit–closure bigcopy: limit–n–5100big3819truefalsetruefalsetruefalsetruefalse!
Violet card: the code (the body of main)Slate: main's variables; khaki: the closure object big; sand: std::count_if and nTokens: values hopping between them, true/false answers, a red ! for a dangling referenceLeft: the code, the body of main. Back right: main's variables, the vector v and limit. Middle: the closure object big. Right: std::count_if and its counter n. The lambda expression on lines 3-5 builds big and copies limit's value, 5, into it. Changing limit to 100 later does not touch the copy. count_if calls big once per element: 8 and 9 are bigger than 5, so n is 2. With [&limit] big reads main's limit, 100, and n is 0. For a capture by reference the standard does not say whether the closure stores anything (a pointer, say); it only says the lambda refers to the original variable. The figure draws it as a link.

The lambda

  1. A lambda expression writes a small function right where you need it. [limit] is the capture list, (int x) the parameters, and the braces hold the body. Lines 3 to 5 make an object, big, that you can call like a function.

Capture

Calling it

Choices

What happens

;; step 1/10 · what
[ captures ] ( parameters ) { body }
  [limit]     what the lambda may use from around it
  (int x)     what it takes when called
  { return x > limit; }   what it does
auto big = ...;   big holds the result: an object
big(7)  calls it like a function → true (7 > 5)

The closure type has no name you can write, and the C++ standard leaves its copied members unnamed too. The class Big in the notes is a model that behaves the same way; it is not literally what the compiler writes. The card shows the body of main. The full program adds #include <algorithm>, <iostream> and <vector>, and prints n with std::cout. Built with g++ or clang++ -std=c++20 -Wall -Wextra it prints 2; with [&limit] on line 3 it prints 0.