In the previous article, we have discussed about CPP 11 Multithreading – Part 2: Joining and Detaching Threads. Let us learn how to Capture Member Variables Inside Lambda Function in C++ Program.
Capturing Member Variables Inside Lambda Function
In this article we are going to see how to capture a member variable inside a lambda function.
We will be using a class Odd to record the odd numbers read by the object. There we will be using the lambda function that would capture the member variable.
We can’t catch a member variable by passing it as a value or by reference. The below example will demonstrate how to not capture member variable.
#include <iostream> #include <vector> #include <algorithm> class Odd { // Couns the variable int variableCounter = 0; public: int Count() { return variableCounter; } void update(std::vector<int> &vec) { // Capturing member variable by value std::for_each(vec.begin(), vec.end(), [variableCounter](int element) { if (element % 2) variableCounter++; // Accessing member variable from outer scope }); } }; int main() { std::vector<int> val = {55, 78, 49, 2323, 11, 1, 25, 4}; Odd obj; obj.update(val); int counterVariable = obj.Count(); std::cout << "Counter is = " << counterVariable; return 0; }
The above code where we pass by value will show error during compilation.
Capturing Member variables inside Lambda Function :
To capture the member variables into lambda function we have to use this
.
#include <iostream> #include <vector> #include <algorithm> class Odd { // Counts the variable int variableCounter = 0; public: int Count() { return variableCounter; } void update(std::vector<int> &vec) { // Capturing member variable by value using THIS std::for_each(vec.begin(), vec.end(), [this](int element) { if (element % 2) variableCounter++; }); } }; int main() { std::vector<int> val = {55, 78, 49, 2323, 11, 1, 25, 4}; Odd obj; obj.update(val); int counterVariable = obj.Count(); std::cout << "Counter is = " << counterVariable; return 0; }
Output : Counter is = 6
In the above program we saw that “this
” which is copied by value inside lambda, so all member variables from outer scope can be accessed directly.