On this page
Lambdas
Prev: Templates | Up: builtins | Next: nullptr
Rel: Algorithms & Ranges, auto
Ref: cppreference — Lambda Expressions
Tags: #public #prog #cpp #builtins #functional #tier/core
Overview
A C++ lambda expression constructs an anonymous, unnamed function object (closure) inline. Because each lambda has its own unique compile-time type, passing it to templated algorithms (std::sort, std::ranges::filter) incurs zero heap allocation and zero indirect-call overhead.
Capture Syntax
int threshold = 10;
auto by_value = [threshold](int x) { return x > threshold; };
auto by_ref = [&threshold](int x) { threshold += x; };
auto moved_in = [ptr = std::make_unique<int>(42)]() { return *ptr; }; // init-capture
auto generic = [](const auto& a, const auto& b) { return a < b; }; // generic lambda
Capture Safety
- Prefer explicit capture lists (
[threshold],[&count]) over default[=]or[&]so lifetime dependencies stay obvious. - Never let a lambda capturing local variables by reference (
[&]) outlive the enclosing function (e.g., when stored in a callback or spawned thread).
Linked from
Related notes
- tuts/cpp/builtins/nullptr Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/templates Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; links to this page; shared tags: #cpp, #prog
- tuts/cpp/builtins/auto Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/sort links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier