Edmund Xin

Lambdas in C++

Lambdas in C++ are similar to normal functions but include a capture list to specify which variables from the surrounding scope can be used in the lambda.

Capture a variable by value

int x = 10; auto f = [x]() { return x + 1; };

Capture a variable by reference

int x = 10; auto f = [&x]() { return x + 1; }; f(); // x becomes 11

Capture all local variables by value/reference

auto f1 = [=]() { return x + y }; // copies all local variables auto f2 = [&]() { return x + y }; // uses references of local variables
Software Engineer