wiki:cpp-lambda-captures
Table of Contents
C++ Lambda captures
Lambda captures are the mechanism by which lambdas access variables from their enclosing scope. Capture by value [x] copies the variable; capture by reference [&x] refers to the original. Default capture [=] or [&] captures all variables in value or reference form; [=, &x] captures most by value but x by reference.
Be careful with lambda captures: prefer explicit captures; avoid capturing by reference if the lambda outlives the variables' scope.
Example
This example shows lambda capture by value and reference with different scopes.
// compile: g++ -std=c++17 -o lambda lambda.cpp // run: ./lambda // description: lambda capture mechanics and lifetime rules #include <iostream> #include <vector> #include <functional> int main() { int x = 42; auto by_value = [x]() { std::cout << "Value: " << x << "\n"; }; auto by_ref = [&x]() { std::cout << "Ref: " << x << "\n"; }; x = 100; by_value(); // prints 42 (captured value) by_ref(); // prints 100 (refers to x) // Safe: capture by value if lambda outlives scope std::vector<std::function<void()>> funcs; { int y = 10; funcs.push_back([y]() { std::cout << "Captured: " << y << "\n"; }); // funcs.push_back([&y]() {...}); // UNSAFE: y destroyed } funcs[0](); // safe: y was captured by value return 0; }
wiki/cpp-lambda-captures.md · Last modified: by 127.0.0.1
