Skip to content

Module 9 · Modern C++ — topic 1 of 3

Lambda Expressions

Lambdas are unnamed function objects written inline. Learn the syntax, captures by value and reference, mutable lambdas, generic lambdas and std::function.

Beginner 15 min read·Lesson 38 of 40 in C++ Programming

Learning objectives

  • Write lambdas with and without captures
  • Choose between capture by value and by reference
  • Pass lambdas to algorithms and store them in std::function

Definition

A lambda expression creates an unnamed function object (closure) that can capture variables from the enclosing scope; its syntax is [captures](parameters) -> return_type { body }.

Introduction

Algorithms like sort and count_if need a small piece of behaviour — a comparison or a condition. Before C++11 you wrote a separate function or functor class; now you write the logic right where it's used.

Why it matters

Lambdas make STL algorithms concise and readable.

Callbacks, event handlers and threads all take lambdas.

Detailed explanation

[] captures nothing; [x] copies x; [&x] refers to x; [=] copies everything used; [&] references everything used; [this] captures the current object.

Captured copies are const inside the lambda unless it is declared mutable.

A reference capture must not outlive the variable — returning a lambda that captured a local by reference creates a dangling reference.

Generic lambdas (C++14) use auto parameters: [](auto a, auto b) { return a < b; }.

Each lambda has a unique type; store one with auto or, when the type must be uniform (e.g. a vector of callbacks), in std::function<R(Args...)> (with some overhead).

Syntax

C++
auto square = [](int x) { return x * x; };
int limit = 50;
auto above = [limit](int m) { return m > limit; };
int count = 0;
std::for_each(v.begin(), v.end(), [&count](int) { ++count; });
std::function<double(double)> f = [](double x) { return x / 2; };
  • The return type is usually deduced.
  • Prefer explicit captures over [=] and [&] in long-lived lambdas.
  • Include <functional> for std::function.

Code examples

Lambdas with algorithms

C++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{5, -2, 9, -7, 3};
std::sort(v.begin(), v.end(), [](int a, int b) { return std::abs(a) < std::abs(b); });
for (int x : v) std::cout << x << ' ';
int limit = 4;
auto n = std::count_if(v.begin(), v.end(), [limit](int x) { return x > limit; });
std::cout << "| above " << limit << ": " << n << '\n';
return 0;
}
Output
-2 3 5 -7 9 | above 4: 2

Value vs reference capture

C++
#include <iostream>
int main() {
int x = 10;
auto by_value = [x] { return x; };
auto by_ref = [&x] { return x; };
x = 20;
std::cout << by_value() << ' ' << by_ref() << '\n';
return 0;
}
Output
10 20

The value capture copied x when the lambda was created.

More examples

mutable, generic lambdas and std::function

C++
#include <functional>
#include <iostream>
#include <map>
#include <string>
int main() {
auto counter = [n = 0]() mutable { return ++n; }; // init-capture with its own state
counter();
counter();
std::cout << "counter: " << counter() << '\n';
auto bigger = [](const auto& a, const auto& b) { return a > b ? a : b; };
std::cout << bigger(3, 9) << ' ' << bigger(std::string("pear"), std::string("apple")) << '\n';
std::map<std::string, std::function<double(double, double)>> ops{
{"+", [](double a, double b) { return a + b; }},
{"*", [](double a, double b) { return a * b; }},
{"avg", [](double a, double b) { return (a + b) / 2; }},
};
for (const auto& [name, op] : ops) std::cout << name << " -> " << op(6, 3) << '\n';
return 0;
}
Output
counter: 3
9 pear
* -> 18
+ -> 9
avg -> 4.5

Step-by-step explanation

  • [n = 0] creates a member n inside the closure; mutable allows changing it.
  • Each call increments the closure's own n: 1, 2, 3.
  • The generic lambda works for ints and strings.
  • std::function stores different lambdas with the same signature in one map (sorted by key: "*", "+", "avg").

Expected output

Running “mutable, generic lambdas and std::function” prints exactly:

TextOutput
counter: 3
9 pear
* -> 18
+ -> 9
avg -> 4.5

Practical applications

  • GUI frameworks connect button clicks to lambdas.
  • Thread pools take lambdas as tasks.
  • Sorting UIs by different columns uses lambda comparators.

Best practices

  • Keep lambdas short; name complex ones.
  • Capture explicitly what you use.
  • Prefer auto over std::function when you don't need type erasure.

Common mistakes

Dangling reference capture

Avoid

std::function<int()> make() { int local = 5; return [&local] { return local; }; }

Prefer

std::function<int()> make() { int local = 5; return [local] { return local; }; }

The local is destroyed when make returns; capture by value instead.

Modifying a value capture

Avoid

auto f = [count]() { ++count; };

Prefer

auto f = [count]() mutable { ++count; };

Captured copies are const unless the lambda is mutable.

Important notes

  • C++20 allows template parameter lists on lambdas: []<typename T>(T x) { ... }.
  • Lambdas with no captures convert to plain function pointers, usable with C APIs.

Key takeaways

  • Lambdas are inline function objects with captures.
  • Value captures copy; reference captures alias.
  • std::function stores any callable with a given signature.

Try it yourself

  1. 1
    Sort a vector of strings by length, then alphabetically, using one lambda.
  2. 2
    Write a function returning a lambda that adds a captured number to its argument.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • ModerateWhat is printed?
Practise this topic