Home C++ Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

C++ 14


Contents

Lambda Capture Initializer

This allows us to define a variable in the capture clause and initizlize it with an expression. The variable can be the same name as one outside the lambda/

File: lambda1.cpp
#include <iostream>

using namespace std ;

int factory(int i)
{
        return i * 10;
}


int main()
{
    int x1 = 100 ;
    //A new x1 is created in the lambda
    auto f1 = [ x1 = 5 ]
        {
            //Does not change the outer x1
            cout << "Inside the lambda " <<  " x1: " <<  x1 << endl ;
            return x1 ;
        }; // returns 20

    cout << "f1() " << f1() << " x1: " <<  x1 << endl ;

    // x1 is an internal variable local to the
    //lambda
    auto f2 = [ x1 = factory(2) ]
    {
        return x1 ;
    }; // returns 20

    cout << "f2() " << f2() << " x1: " <<  x1 << endl ;

    auto generator = [x2 = 0] () mutable {
      // this would not compile without 'mutable' as we are modifying x on each call
      return x2++ ;
    };
    auto a1 = generator(); // == 0
    auto b1 = generator(); // == 1
    auto c1 = generator(); // == 2


   cout << "a1: " << a1  << endl ;
   cout << "b1: " << b1  << endl ;
   cout << "c1: " << c1  << endl ;

}