A lambda is a function you write where you use it, without giving it a name.
The Analogy: A Sticky Note Instead of a Filing Cabinet
Named functions are like documents in a filing cabinet. Each one has a label, a place, and a life of its own — anybody can pull it out and use it. That is exactly what you want for a procedure that many parts of the program need.
But sometimes you need an instruction that is only meaningful right here: "sort these by the third character", "skip the entries older than this cutoff", "when the download finishes, add one to my counter". Filing those away under formal names is bureaucracy — you invent a name nobody will ever say out loud, put it hundreds of lines away from the only place it matters, and the reader has to go fetch it to understand the line they are looking at.
A lambda is the sticky note. You write the instruction on the spot, hand it straight to whoever needs it, and it disappears when the scope ends. Crucially, a sticky note can also mention things sitting on the desk around it — the cutoff date, the counter — and that is the capture: the part of a lambda that has no equivalent in a plain function.
Syntax or Core Structure
The full shape is [capture](parameters) -> returnType { body }, and most of it is optional:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
// 1. The minimum: no captures, no parameters.
auto greet = []() { std::cout << "hello\n"; };
greet();
// 2. Parameters and a deduced return type.
auto add = [](int a, int b) { return a + b; };
std::cout << "add: " << add(3, 4) << "\n";
// 3. An explicit return type, when deduction is not what you want.
auto divide = [](int a, int b) -> double { return static_cast<double>(a) / b; };
std::cout << "divide: " << divide(7, 2) << "\n";
// 4. Empty parentheses are optional when there are no parameters.
auto shout = [] { std::cout << "OI\n"; };
shout();
// 5. Capture by value: a snapshot taken when the lambda is created.
int limit = 10;
auto underLimit = [limit](int n) { return n < limit; };
limit = 0; // does not affect the lambda
std::cout << "5 under limit? " << underLimit(5) << "\n";
// 6. Capture by reference: talks to the original variable.
int counter = 0;
auto bump = [&counter]() { ++counter; };
bump(); bump(); bump();
std::cout << "counter: " << counter << "\n";
// 7. Passed straight into an algorithm -- the everyday use.
std::vector<std::string> names{"Ada", "Grace", "Alan", "Edsger"};
std::sort(names.begin(), names.end(),
[](const std::string& a, const std::string& b) {
return a.size() < b.size();
});
for (const auto& n : names) std::cout << n << " ";
std::cout << "\n";
// 8. Using a captured value inside an algorithm.
std::size_t maxLength = 4;
auto shortCount = std::count_if(names.begin(), names.end(),
[maxLength](const std::string& n) { return n.size() <= maxLength; });
std::cout << "short names: " << shortCount << "\n";
// 9. Immediately invoked, to initialise a const from a few steps.
const int total = [&names] {
int sum = 0;
for (const auto& n : names) sum += static_cast<int>(n.size());
return sum;
}();
std::cout << "total letters: " << total << "\n";
return 0;
}
Output:
hello
add: 7
divide: 3.5
OI
5 under limit? 1
counter: 3
Ada Alan Grace Edsger
short names: 2
total letters: 18
Read the pieces in order. [] is the capture list and is never optional — it is what tells the compiler this is a lambda at all. The parameters, the -> type, and the body then behave like any function's. Case 5 and case 6 are the whole difference between the two capture styles: [limit] copied the value 10 at the moment the lambda was created, so changing limit afterwards changed nothing, while [&counter] bound to the variable itself and the three calls were visible outside.
Case 9 deserves a second look: the lambda is defined and called on the same line with the trailing (). That "immediately invoked lambda" is the standard way to run several statements while still declaring the result const.
Technical Depth: What a Lambda Really Is
It is a class, not a function
The compiler turns every lambda into an unnamed struct with an operator(). These two are essentially the same thing:
auto underLimit = [limit](int n) { return n < limit; };
// roughly what the compiler generates:
struct __Lambda1 {
int limit; // one member per capture
bool operator()(int n) const { return n < limit; }
};
__Lambda1 underLimit{limit};
Three consequences follow immediately, and they explain almost every lambda rule:
- Captures are members, so a lambda has a size.
[]captures nothing and is typically 1 byte; capturing threeints makes it 12. operator()isconstby default, which is why modifying a by-value capture will not compile withoutmutable.- Every lambda has a distinct type, even two that are character-for-character identical, which is why you store one in
autoand not in a named type.
The capture list in full
| Capture | Meaning |
|---|---|
[] | Nothing. The lambda uses only its parameters and globals. |
[x] | Copy x at creation time. |
[&x] | Refer to x. It must outlive the lambda. |
[x, &y] | Mix freely. |
[=] | Copy everything mentioned in the body. |
[&] | Refer to everything mentioned in the body. |
[this] | Capture the enclosing object's this pointer (members by reference). |
[*this] | C++17: copy the whole enclosing object. |
[total = 0] | C++14 init-capture: a new lambda member, initialised here. |
[p = std::move(ptr)] | Move something non-copyable into the lambda. |
[=] and [&] look convenient and are worth resisting. [&] inside a function that returns the lambda is a dangling-reference generator; [=] quietly copies whatever the body happens to mention, so adding one line to the body can add a large copy. Name what you capture — the list then documents exactly what the lambda depends on.
mutable, and the state a lambda can keep
int start = 5;
// auto broken = [start]() { return ++start; }; // ERROR: operator() is const
auto ticker = [start]() mutable { return ++start; };
std::cout << ticker() << ticker() << ticker(); // 678
std::cout << start; // 5 -- the original is untouched
mutable makes operator() non-const, so the lambda can modify its own copies. The lambda now carries state between calls — a small object with memory, which is exactly what a plain function cannot be.
Value versus reference, and lifetime
auto makeBroken() {
int local = 42;
return [&local] { return local; }; // DANGLING: local dies here
}
auto makeFine() {
int local = 42;
return [local] { return local; }; // safe: the value came along
}
The rule of thumb: capture by reference for a lambda you call immediately (an algorithm predicate, a loop body), and capture by value for a lambda you store, return, or hand to another thread. A callback that runs "later" and captures by reference is the classic asynchronous crash.
Init-capture handles the case where the thing is neither copyable nor safe to reference:
auto session = std::make_unique<Session>();
auto task = [s = std::move(session)] { s->run(); }; // the lambda now owns it
Capturing this in a member function
struct Counter {
int value = 0;
void addAll(const std::vector<int>& xs) {
std::for_each(xs.begin(), xs.end(),
[this](int x) { value += x; }); // members by reference
}
};
[this] captures the pointer, so the lambda is only valid while the object is. Note that [=] in a member function also captures this by pointer — it does not copy the object, despite looking like it should. That mismatch is why C++20 deprecated implicit this capture through [=], and why [*this] exists for when you genuinely want a snapshot of the object.
Generic lambdas and the return type
auto larger = [](const auto& a, const auto& b) { return a < b ? b : a; }; // C++14
std::cout << larger(3, 9) << " " << larger(std::string("ab"), std::string("z"));
// Explicit template parameters, C++20:
auto sum = []<typename T>(const std::vector<T>& v) {
return std::accumulate(v.begin(), v.end(), T{});
};
An auto parameter makes the lambda's operator() a template — one lambda, many types. Deduced return types follow the same rule as functions: all return statements must agree, and a deduced return strips references, so a lambda meant to hand back an element needs -> Item& or decltype(auto).
Storing a lambda: auto versus std::function
| Holder | Cost | Use when |
|---|---|---|
auto | Zero. Fully inlinable. | The lambda stays in one scope. |
template <typename F> parameter | Zero. Inlinable at each call site. | Passing a callable into your own function. |
std::function<int(int)> | Indirect call, possible heap allocation. | Storing callables of different types together, or in a class member. |
Function pointer int(*)(int) | Zero, but no captures allowed. | Interfacing with a C API. |
A capture-less lambda converts implicitly to a plain function pointer, which is how you feed one to a C callback. A capturing lambda cannot — it has state, and a function pointer has nowhere to put it.
Lambda versus the alternatives
| Approach | Verdict |
|---|---|
| Named function | Best when reused, or when the logic needs a name and a test. |
| Lambda | Best when short, local, and dependent on nearby variables. |
Function object (struct with operator()) | Only when you need extra members, typedefs, or a named type. |
std::bind | Legacy. A lambda is clearer and faster in every case. |
Real World Example: A Composable Log Filter
Lambdas are at their most powerful when a function returns one. Each of the small factory functions below builds a filter out of the arguments it was given, and allOf combines filters into a bigger filter — so the caller describes a query in one readable expression instead of writing a nested if.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <functional>
#include <algorithm>
struct LogEntry {
int timestamp;
std::string level;
std::string source;
std::string message;
};
using Filter = std::function<bool(const LogEntry&)>;
int levelRank(const std::string& level) {
if (level == "ERROR") return 3;
if (level == "WARN") return 2;
if (level == "INFO") return 1;
return 0; // DEBUG and anything unknown
}
Filter minLevel(const std::string& level) {
const int floorRank = levelRank(level); // computed once, not per entry
return [floorRank](const LogEntry& e) {
return levelRank(e.level) >= floorRank;
};
}
Filter after(int timestamp) {
return [timestamp](const LogEntry& e) { return e.timestamp > timestamp; };
}
Filter fromSource(std::string source) {
return [source = std::move(source)](const LogEntry& e) {
return e.source == source;
};
}
Filter containing(std::string needle) {
return [needle = std::move(needle)](const LogEntry& e) {
return e.message.find(needle) != std::string::npos;
};
}
Filter notMatching(Filter inner) {
return [inner = std::move(inner)](const LogEntry& e) { return !inner(e); };
}
Filter allOf(std::vector<Filter> filters) {
return [filters = std::move(filters)](const LogEntry& e) {
return std::all_of(filters.begin(), filters.end(),
[&e](const Filter& f) { return f(e); });
};
}
void report(const std::string& heading,
const std::vector<LogEntry>& log,
const Filter& keep) {
std::cout << heading << "\n";
int shown = 0;
std::for_each(log.begin(), log.end(), [&](const LogEntry& e) {
if (!keep(e)) return;
++shown;
std::cout << " [" << e.timestamp << "] " << e.level
<< " " << e.source << ": " << e.message << "\n";
});
std::cout << " matched " << shown << " of " << log.size() << "\n\n";
}
int main() {
const std::vector<LogEntry> log{
{100, "INFO", "auth", "user ada signed in"},
{140, "DEBUG", "cache", "warm start, 0 keys"},
{180, "WARN", "auth", "slow password hash"},
{220, "ERROR", "db", "connection refused"},
{260, "INFO", "db", "retrying connection"},
{300, "ERROR", "db", "connection refused"},
{340, "INFO", "auth", "user grace signed in"},
{380, "WARN", "cache", "eviction storm"},
};
// A stateful lambda: its own counter, no global, no class.
auto nextTicket = [n = 0]() mutable { return ++n; };
std::cout << "ticket ids: ";
std::cout << nextTicket() << " ";
std::cout << nextTicket() << " ";
std::cout << nextTicket() << "\n\n";
// Capture by reference, because this runs right now.
std::map<std::string, int> byLevel;
std::for_each(log.begin(), log.end(),
[&byLevel](const LogEntry& e) { ++byLevel[e.level]; });
std::cout << "Level tally:\n";
for (const auto& [level, count] : byLevel) {
std::cout << " " << level << " " << count << "\n";
}
std::cout << "\n";
report("WARN and above, after t=150:", log,
allOf({minLevel("WARN"), after(150)}));
report("db, excluding 'refused':", log,
allOf({fromSource("db"), notMatching(containing("refused"))}));
report("auth only:", log, fromSource("auth"));
return 0;
}
Output:
ticket ids: 1 2 3
Level tally:
DEBUG 1
ERROR 2
INFO 3
WARN 2
WARN and above, after t=150:
[180] WARN auth: slow password hash
[220] ERROR db: connection refused
[300] ERROR db: connection refused
[380] WARN cache: eviction storm
matched 4 of 8
db, excluding 'refused':
[260] INFO db: retrying connection
matched 1 of 8
auth only:
[100] INFO auth: user ada signed in
[180] WARN auth: slow password hash
[340] INFO auth: user grace signed in
matched 3 of 8
Every capture choice here is deliberate, and each one illustrates a different rule.
The factories all capture by value, because the lambdas they return outlive the function call that made them. minLevel captures floorRank rather than the level string — the ranking is resolved once, at construction, so the returned filter never touches the string again. Had it captured the std::string and called levelRank on it per entry, the filter would repeat the same three comparisons for every line in the log. This is the small design win that returning a lambda buys you: work that depends only on the configuration can be done before the loop starts.
fromSource, containing, notMatching and allOf all use the C++14 init-capture form [x = std::move(x)]. The parameter is taken by value and then moved into the lambda, so a caller's temporary string or vector is transferred rather than copied twice. notMatching and allOf are the interesting ones — they capture other std::function objects, which is what makes filters composable at all. Note that allOf's inner lambda captures [&e] by reference: that one runs immediately inside std::all_of, within a single call, so a reference is both safe and free.
report's lambda uses [&] — the one place in this program where the catch-all is reasonable, because it is a loop body passed straight to std::for_each and never stored. It needs shown by reference to count, and keep by reference to avoid copying a std::function. Compare it with nextTicket, whose [n = 0]() mutable gives the lambda a private member it can increment across calls: a counter with no surrounding class and no global variable, whose lifetime is exactly the scope it was declared in.
std::function<bool(const LogEntry&)> is the right holder here even though it costs an indirect call. Every filter has a different lambda type, so auto could not put them in the same std::vector, and allOf could not accept a mixed list. That is the trade this design makes on purpose: if the filters were fixed at compile time, a variadic template taking the lambdas by type would inline the whole chain and be faster — but the query would have to be written by the programmer, not assembled at runtime from user input.
Common Mistakes
- Returning a lambda that captured by reference.
return [&local] { return local; };compiles and then reads freed stack memory. If the lambda outlives the scope, capture by value or with an init-capture. - Using
[&]or[=]out of habit.[&]in a stored or asynchronous callback is a dangling reference;[=]silently copies whatever the body mentions, so an innocent new line in the body can add a large copy. Name your captures. - Trying to modify a by-value capture.
[count]() { ++count; }will not compile, becauseoperator()isconst. Addmutableif you want the lambda's own copy to change, or capture by reference if you meant the original. - Expecting
mutableto write back.mutablemodifies the lambda's copy only. The variable outside never changes. - Assuming
[=]copies the object in a member function. It capturesthisby pointer, so the lambda dies with the object. Use[*this]for a real snapshot. - Storing every lambda in
std::function. For a predicate handed tostd::sort, that adds an indirect call per comparison for no reason. Useauto, or a template parameter. - Capturing a
std::unique_ptrby value. It is not copyable, so[p]fails. Use[p = std::move(p)]. - A capturing lambda where a function pointer is required. C APIs take
void(*)(void*); only a capture-less lambda converts. Use the trampoline pattern instead. - Letting a lambda grow. Once the body passes a dozen lines or needs its own tests, it wants a name. A lambda is not a substitute for a function.
Best Practices
- Capture explicitly by name. The capture list is documentation of what the lambda depends on.
- Capture by reference for lambdas you call now, by value for lambdas you store, return, or send to another thread.
- Store lambdas in
auto; accept them astemplate <typename F>parameters; reach forstd::functiononly when different callable types must share a type. - Use init-capture (
[x = std::move(x)]) to move ownership into a lambda, and to precompute values the lambda needs on every call. - Prefer
const auto¶meters for lambdas taking container elements. - Use an immediately invoked lambda to build a
constvalue that takes several statements. - Keep bodies to a few lines; give anything larger a real name.
- Prefer a lambda over
std::bindin all new code.
Practice Exercises
- Write
auto makeAccumulator()that returns a lambda keeping a running total: calling it with5then3should return5then8. Use an init-capture plusmutable, and then explain in a comment why capturing a localintby reference would have been a bug. - Given
std::vector<std::string> words, sort it three ways using lambdas: alphabetically, by length with an alphabetical tie-break, and case-insensitively. Store the third comparator in a namedautovariable and reuse it forstd::max_element. - Extend the log filter above with
anyOf(std::vector<Filter>)andbetween(int from, int to), then build a query for "ERROR entries from db, or anything at all between t=100 and t=150". Work out the expected output by hand before running it. - Take this broken snippet and produce two fixed versions — one capturing by value, one using an init-capture — explaining what each does differently:
std::vector<std::function<void()>> tasks; for (int i = 0; i < 3; ++i) { int local = i * 10; tasks.push_back([&local] { std::cout << local; }); }followed by calling every task.