Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Lambda expressions and captures

A lambda expression creates a callable object. Learn capture by copy and reference, init-capture, the meaning of mutable, and generic lambdas with auto parameters.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

[captures](parameters) mutable -> ReturnType { body }

A lambda expression creates a closure object with a unique, unnamed class type. You can store it in an auto variable and call it like a function. The syntax shown is schematic: captures, parameters, ReturnType, and body are placeholders; mutable and -> ReturnType are optional.

For a local int x, [x] stores a copy of its value, while [&x] means capture by reference: operations affect the original. [] captures nothing; [=] and [&] specify the default capture mode for needed variables. A reference does not extend the object's lifetime: invoking a lambda that uses a destroyed object has undefined behavior.

An init-capture, such as [count = start], initializes closure state when the closure is created. For an ordinary lambda without an explicit object parameter, the call operator is const by default. A mutable lambda allows modification of non-const state captured by copy, without thereby changing the original. Modifying an object through a captured reference does not require mutable.

A generic lambda has an auto parameter or an explicit template parameter list; its call operator is a template. In the example, add combines these mechanisms: count retains changes between calls, total is modified through a reference, and start remains 10.

This entry targets C++23. The supplied sources are an evolving working draft, not a frozen C++23 text; the example does not use later extensions. A repository compiler flag does not attest the production runtime.

Examples

#include <iostream>

int main() {
    int total = 0;
    int start = 10;
    auto add = [&total, count = start](auto value) mutable {
        ++count;
        total += value;
        return count;
    };

    const auto first = add(3);
    const auto second = add(4);
    std::cout << first << ' ' << second << ' '
              << total << ' ' << start << '\n';
}

Result

11 12 7 10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources