Edmund Xin

C++ Lambdas

Lambdas are an anonymous function object in C++ that you can define inline without needing to write a separate function or functor class.

Basic Syntax

auto lambda = [capture](params) -> return_type { body };

Capture By Value [x]

[!Warning] A copy of the captured variables are made when the lambda is created, not called.

int x = 10; auto f = [x]() { return x * 2; }; x = 99; std::cout << f(); // prints 20 — captured the old copy

[!Warning] By default, value captures are const so the mutable keyword is needed to modify the internal copy.

int counter = 0; auto inc = [counter]() mutable { return ++counter; }; inc(); // returns 1 inc(); // returns 2 — internal copy persists across calls // `counter` outside is still 0

Capture By Reference [&x]

Capture-all [=] and [&]

Software Engineer