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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.