Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Capture by copy in C++ lambdas

Capture a threshold by value so the predicate keeps using it even when the original variable changes.

Version: ISO C++23; implementation support may vary

Syntax

[cost](int price) { return price <= cost; }  // explicit capture by copy
[=](int price) { return price <= cost; }     // implicit capture by copy of an eligible local
[&cost](int price) { return price <= cost; } // explicit capture by reference
[cost]() mutable { return ++cost; }         // modifies the stored copy of a non-const int
[limit = cost](int price) { return price <= limit; } // init-capture (C++14)

Evaluating a lambda expression creates a closure object. In a capture by copy, [cost] directly initializes a member of that object from the current local cost at that point, not when the lambda is called. [=] makes copy capture the default for implicitly captured locals; it does not copy every variable in scope. [limit = cost] is an init-capture (since C++14) that stores the value under the new name limit.

For a non-static lambda without an explicit object parameter, operator() is const by default. mutable removes that restriction so the body can change a non-const stored copy, not the original. It does not strip const from a member and cannot be combined with an explicit object parameter (C++23). A lambda declared static (since C++23) instead has a static call operator, which is not const-qualified.

[&cost] refers to the original and sees later changes. It does not extend the original's lifetime; accessing it after that lifetime ends can cause undefined behavior. A stored int can outlive the original as part of the closure, but copying a raw pointer neither copies its pointee nor keeps it alive.

For a const vector, std::vector::begin and std::vector::end return const_iterator. They mark a half-open range from the beginning to the past-the-end position, which must not be dereferenced. std::count_if counts elements for which the predicate returns true. Here price <= cost is a pure comparison against the stored threshold: it changes neither the elements nor any state.

Use #include directly for <algorithm>, <iostream>, and <vector> rather than relying on transitive includes. The stream insertion operator << sends the count and '\n' to std::cout. The newline alone does not request a stream flush; std::endl adds a newline and calls flush().

Examples

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

int main() {
    const std::vector<int> prices{4, 7, 10, 12};
    int cost = 10;
    const auto within_budget = [cost](int price) {
        return price <= cost;
    };

    cost = 4;
    std::cout << std::count_if(prices.begin(), prices.end(), within_budget) << '\n';
}

Result

3

After `cost = 4`, the predicate still uses the stored `10`: `4`, `7`, and `10` pass. The program prints `3`; with `[&cost]` it would print `1`.

Related lessons

  • C++ · Lesson 40 · Advanced · Version: 3

Sources