how to capture a pointer in lambda function in CPP
时间: 2024-02-21 07:59:21 浏览: 219
In C++, you can capture a pointer in a lambda function by specifying the pointer in the lambda's capture list.
The capture list is a comma-separated list of variables or expressions that you want to capture. To capture a pointer, you can use the syntax `[&ptr]` to capture the pointer by reference, or `[=ptr]` to capture the pointer by value.
Here's an example:
```
int* ptr = new int(42);
auto lambda = [&ptr]() {
int value = *ptr;
std::cout << "The value of the pointer is: " << value << std::endl;
};
lambda(); // prints "The value of the pointer is: 42"
delete ptr; // make sure to delete the pointer when you're done with it
```
In this example, we create a lambda function that captures the `ptr` pointer by reference using the `&` symbol in the capture list. Inside the lambda function, we dereference the pointer to get the value it points to, and print it to the console.
Note that if you capture a pointer by reference, you need to make sure that the pointer remains valid for the lifetime of the lambda function. If the pointer goes out of scope or is deleted before the lambda is executed, you may get undefined behavior.
阅读全文
相关推荐












