What is Lambda Capture?

Before looking into *this capture, let’s see how lambda capture works in C++. In C++, lambdas are a way to create anonymous functions, which can capture variables from their enclosing scope. There are two primary capture modes: by value and by reference.

Lambda Capture of *this in C++17

In C++, a lambda function can capture variables from the enclosing scope using capture clauses. Lambda functions can also be used to capture this pointer, which allows us to access class members and methods within the lambda. In this article, we will learn how Lambda Capture of *this pointer is changed in C++17.

Similar Reads

What is Lambda Capture?

Before looking into *this capture, let’s see how lambda capture works in C++. In C++, lambdas are a way to create anonymous functions, which can capture variables from their enclosing scope. There are two primary capture modes: by value and by reference....

Capturing *this in C++ 17

Earlier, we could only capture this pointer by reference. This leads to problems when the referenced object is temporary or goes out of scope leading to the dangling reference. The capture of *this by value was added in C++ 17 to avoid these problems....

Syntax

We just have to define the capture clause of lambda expression like this:...

Example

C++ // C++ Program to illustrate by value capture of *this // in lambda expressions #include using namespace std;    class Counter { public:     Counter()         : count(0)     {     }        void Increment()     {         // Define a lambda that captures *this by value         auto incrementLambda = [*this]() mutable {             // Access the count member variable and             // increment it             count++;         };            // Call the lambda to perform the increment         incrementLambda();     }        int GetCount() const { return count; }    private:     int count; };    int main() {     // Create an instance of the Counter class     Counter counter;        // Call the Increment method, which uses a lambda to     // increment the count     counter.Increment();     counter.Increment();        // Retrieve and print the updated count     cout << "Count: " << counter.GetCount() << endl;        return 0; }...

Contact Us