Skip to content
Quantoros

What does each lambda capture mode mean: [], [=], [&], [this], init captures?

C++Level: IntermediateModern C++ Features

What does each lambda capture mode mean: [], [=], [&], [this], init captures?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

Lambda Syntax Overview

:Source: src/lambda/syntax

A lambda expression consists of a capture clause, parameter list, optional specifiers, and a body. The capture clause [] determines which variables from the enclosing scope are accessible inside the lambda. The compiler generates a unique closure type for each lambda, with operator() containing the lambda body.

// [capture](parameters) specifiers -> return_type { body }

#include <iostream>

int main() {
  int x = 10;

  auto by_value = [x]() { return x * 2; };        // Capture x by value
  auto by_ref = [&x]() { x *= 2; };               // Capture x by reference
  auto all_val = [=]() { return x; };             // Capture all by value
  auto all_ref = [&]() { x = 0; };                // Capture all by reference

  std::cout << by_value() << "\n";  // Output: 20
}

Answer section

Init Capture (C++14)

:Source: src/lambda/init-capture

C++14 introduced init capture (also called generalized lambda capture), allowing you to create new variables in the capture clause with arbitrary initializers. This enables move-capturing, renaming variables, and capturing expressions. Init capture is essential for capturing move-only types like std::unique_ptr.

#include <iostream>
#include <memory>
#include <utility>

int main() {
  auto ptr = std::make_unique<int>(42);

  // Move-capture: transfers ownership into lambda
  auto f = [p = std::move(ptr)]() { std::cout << *p << "\n"; };
  f();  // Output: 42

  // ptr is now nullptr

  // Capture with expression
  int x = 10;
  auto g = [y = x * 2]() { return y; };
  std::cout << g() << "\n";  // Output: 20
}

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions