How do lambda captures work in C++?

CaptureMeaning
[x]x by value
[&x]x by reference
[=]All used variables by value
[&]All used variables by reference
[this]The current object pointer
[x = std::move(y)]Init capture (C++14): create a member
#include <iostream>
#include <memory>

int main() {
    int a = 1, b = 2;
    auto f = [a, &b] { b += a; return b; };
    std::cout << f() << ' ' << b << '\n';

    auto p = std::make_unique<int>(7);
    auto g = [q = std::move(p)] { return *q; };        // move into the lambda
    std::cout << g() << ' ' << (p == nullptr) << '\n';
}
Output

3 3
7 1

A lambda which is saved or returned must not capture local variables by reference, because the variables are destroyed. See Lambda Expressions.


Learn more about the similar topics:
Tutorials
C++ Lambda Expressions
C++ Move Semantics and the Rule of Five
Modern C++ Features: ranges, optional, variant and format
C++ Multithreading: thread, mutex and async
Exercises & Assignments
Filter and sum numbers with algorithms and ranges
Interview Questions & Answers
What is the Rule of Three, Five and Zero in C++?
What does std::move do in C++?
What are concepts in C++20?
What is perfect forwarding in C++ (std::forward)?
How do lambda captures work in C++?
What is new in C++20?
What is new in C++23?