what is the cpature in CPP lambda function
时间: 2024-02-21 07:00:03 浏览: 20
In C++ lambda functions, the capture clause allows you to specify which variables from the surrounding context are accessible inside the lambda body.
There are two types of captures in C++ lambda functions:
- Value capture: It captures the value of the variable at the time of the lambda creation
- Reference capture: It captures the reference to the variable, allowing the lambda to modify the original variable.
The capture clause comes after the parameter list and before the function body in the lambda function declaration. It is enclosed in square brackets ([]), which can be followed by either an equal sign (=) or an ampersand (&).
Here is an example of a lambda function that captures a variable by value:
```
#include <iostream>
int main() {
int x = 5;
auto lambda = [x]() {
std::cout << "x = " << x << std::endl;
};
lambda(); // Output: x = 5
return 0;
}
```
In this example, the variable `x` is captured by value in the lambda function by including it in the capture clause ([]). The lambda function copies the value of `x` at the time of creation and stores it in its own internal state. When the lambda is called, it prints the value of `x`. The output is `x = 5`, which is the value of `x` at the time of the lambda creation.
Here is an example of a lambda function that captures a variable by reference:
```
#include <iostream>
int main() {
int x = 5;
auto lambda = [&x]() {
std::cout << "x = " << x << std::endl;
x = 10;
};
lambda(); // Output: x = 5
std::cout << "x = " << x << std::endl; // Output: x = 10
return 0;
}
```
In this example, the variable `x` is captured by reference in the lambda function by including it in the capture clause ([]). The lambda function stores a reference to the variable `x` in its internal state, allowing it to modify the original variable. When the lambda is called, it prints the value of `x`, which is `5`. The lambda function also modifies `x` to `10`. After the lambda is called, the value of `x` is printed, which is `10`.