Home >Backend Development >C++ >How to implement closure in C++ Lambda expression?
C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list] (parameters) -> return-type { function-body }. capture-list defines the variables to capture, you can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2, ...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.
Closures in C++ Lambda expressions
A closure is a set of related variables that are stored within the function scope In addition, functions can access these variables at the same time. In C++, closures are implemented through lambda expressions to capture variables in the execution context of a function.
Syntax
The general syntax of C++ Lambda expression is as follows:
[capture-list] (parameters) -> return-type { function-body }
wherecapture-list
defines the variables to be captured , can be used in the following ways:
[=]
: Capture all local variables by value [&]
: Capture all local variables Variables by reference[variable1, variable2, ...]
: Capture specific variables by value or referencePractical case
Let us consider a Lambda expression that needs to access its outer function scope variable. The following code snippet demonstrates this functionality:
#include <iostream> int main() { int value = 10; auto lambda = [value] () { std::cout << value << std::endl; }; lambda(); // 输出 10 return 0; }
In this example, the Lambda expression captures the value
variable by value and can be accessed within its function body.
Note
mutable
modifier to modify the captured variable by value inside a Lambda expression. The above is the detailed content of How to implement closure in C++ Lambda expression?. For more information, please follow other related articles on the PHP Chinese website!