C++ Lambda Expressions: Syntax, Closures, Capture Modes & Generic Lambdas

A Lambda Expression is an anonymous (unnamed) inline function object that can capture variables from its enclosing scope. Introduced in C++11, lambdas are indispensable when writing concise callbacks and algorithms.

Capture Modes Breakdown

  • []: Empty capture clause (accesses only its arguments).
  • [=]: Captures all local variables in scope by value (read-only copy).
  • [&]: Captures all local variables in scope by reference (can modify originals).
  • [this]: Captures the current class object instance pointer.
  • [x, &y]: Captures variable x by value and variable y by reference.

Generic Lambda (C++14) with STL Algorithm

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {5, 12, 18, 7, 25, 30};
    int threshold = 15;

    // Capture threshold by value, take element by const reference
    int count = std::count_if(numbers.begin(), numbers.end(), [threshold](int n) {
        return n > threshold;
    });

    std::cout << "Numbers greater than " << threshold << ": " << count << "\n"; // 3

    // Generic auto lambda (C++14):
    auto printer = [](const auto& item) {
        std::cout << "[ITEM]: " << item << "\n";
    };
    printer(42);
    printer("Modern C++");

    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the anatomy of a C++ Lambda expression?

A lambda expression consists of 4 parts: [captures] (parameters) mutable specifiers -> return_type { body }. The capture clause binds surrounding variables into the lambda closure.

Q2. What is the danger of capturing by reference [&] in asynchronous or thread lambdas?

If a lambda captures local variables by reference and runs in a separate background thread after the enclosing function exits, the captured references become dangling pointers, crashing the program. Always capture by value [=] for background tasks.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

STL Algorithms

Passing inline lambdas to std::sort and std::count_if.

C++ Functions

Compare named functions vs anonymous lambdas.

Multithreading

Spawning threads with inline lambda workers.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!