Module lessons (2/4)
Lambda Expressions and Capture Lists
Syntax [captures](parameters) -> return, capture by value vs reference [&], mutable and generic lambda auto.
What you'll learn in this lesson
- Write anonymous inline functions (lambda) with syntax
capture -> ret { body }. - Precisely choose between capture by value
[x], by reference[&x], or[=]/[&]. - Write reusable callbacks with generic lambdas (
auto) and understand the zero cost compared tostd::function.
Overview
Since C++11 lambda expressions allow you to define small anonymous behaviors directly at the point of use. Under the hood, the compiler turns each lambda into an anonymous unique struct with operator(), allowing full inlining with no runtime cost.
A lambda has three main parts: capture list [...], parameter list ( ... ), and body { ... } (the return type is almost always inferred automatically):
Sections covered in this lesson
- 11. Anatomy of a Lambda Expression
- 22. Capture Lists: Value
[x]vs Reference[&x] - 33. Generic Lambdas (
auto) and Keywordmutable - 44. Callback with
autovsstd::function - 5Practical exercises
- 6Check for understanding
Unlock "Lambda Expressions and Capture Lists" and the full Course C++ curriculum
Syntax [captures](parameters) -> return, capture by value vs reference [&], mutable and generic lambda auto.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course C++ plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.