In this article we will discuss how to capture member variables from outer scope.

Suppose we have a class OddCounter to keep the track of odd numbers read by the object. Inside its member function we are creating a lambda function and passing to a STL algorithm std::for_each.

Now this lambda function needs to capture member variable mCounter. How to do it?

If we try to capture member variable directly by value or reference, then it will not work i.e.

Wrong way to capture member variable — Compile Error

It will result in compile error. So how to capture member variables inside lambda function ?

Capturing Member variables inside Lambda Function

To capture the member variables inside lambda function, capture the “this” pointer by value i.e.

Capturing this pointer inside lambda function will automatically capture all the member variables for this object inside lambda.

Complete example is as follows,

Output

Now as “this” is copied by value inside lambda, all member variables from outer scope can be accessed directly.

To compile the above code in linux use following command,

g++ –std=c++11 example.cpp

 

C++11 Lambda Function : Example & Tutorial

C++11 Lambda : How to capture local variables inside Lambda ?

Click Here to Subscribe for more Articles / Tutorials like this.