CodeBlanks Logo Icon CodeBlanks

Capture modes

Learn capture modes with [=], [&] and [this].

Capture modes

The capture clause sets how a lambda captures variables from its surroundings. There are three main modes: [=] captures all variables by value (copy), [&] captures all variables by reference, [this] captures the class this pointer.

With by-value capture the lambda takes a copy; it does not modify the outer variable. With by-reference capture the lambda accesses the outer variable directly; changes propagate outside. You can capture a single variable too: [&count] captures only count by reference. Mixed modes are possible: [=, &count] captures all by value and count by reference.

Value vs reference

By-value capture [=] creates a copy. Even if you modify the variable inside the lambda, the outer variable does not change. By-reference capture [&] gives direct access; changes inside the lambda affect the outer variable.

Example: int n = 0; auto f = [&n]() { n++; }; f(); f(); leaves n at 2. Because the lambda captured n by reference and incremented it each call. If we had used [=], n would not change; the copy inside the lambda would increment but not propagate. Be careful with by-reference capture: the lambda must be used while the reference is still valid.

Practice Increment a counter by reference

Define int count = 0;. Assign the lambda [&count]() { count++; } to the variable increment. Call the lambda twice and print count with std::cout.

Starter code

main.cpp
#include <iostream>

int main() {
    int count = 0;
    // Write a lambda that increments count by reference, call twice
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int count = 0;
    auto increment = [&count]() { count++; };
    increment();
    increment();
    std::cout << count;
    return 0;
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each capture mode to its meaning

Term Meaning
[=] Capture by value
[&] Capture by reference
[this] Class pointer
[&count] Single variable reference

2 Complete the reference capture

Question
int count = 0;
auto f = [____]() { count++; };
Answer
int count = 0;
auto f = [&count]() { count++; };

Explanation: [&count] captures count by reference.

3 Which capture mode can modify an outer variable?

main.cpp
int n = 0;
auto f = ???() { n++; };
  • [=] (by value)
  • [] (no capture)
  • [this]
  • [&] (by reference) Correct answer

Explanation: [&] captures by reference and can modify the outer variable.

All lessons in Intermediate