C++11 Lambda Functions: Intro

Lambda functions are one of the most interesting new features in C++11. Basically lambda functions allow for anonymous inline function objects to be created at the point of use. In versions of C++ prior to C++11, callable function objects are defined in a different location than where they are used. To demonstrate quickly how lambdas are used consider the following example. In C++03, we may define a struct with a function call operator defined.

struct doubleIt {
  int operator()(int val) const {
    return 2*val;

And then in some other code we would instantiate and call the object.

int i = 3;

doubleIt d;
std::cout << d(i) << std::endl;

The analogous C++11 version of this would be simply:

std::cout << [](int val){ return 2*val; }(i) << std::endl;

With the C++11 auto keyword, we can easy assign the callable lambda object to a variable without even knowing the type of the object.

int i = 3;

auto f = [](int val){ return 2*val; };
std::cout << f(i) << std::endl;

Values of variables used within the lambda object can be made available to the body of the lambda using a number of techniques. In the preceding example the value of val we passed in at point of the function call by the value of i. We could also have instead captured variable i from the enclosing scope by either value or reference.

int i = 3;

// Capture local variable i by value
auto f_value = [=](){ return 2*i; };
std::cout << f_value() << std::endl;

// Capture local variable i by reference
auto f_ref = [&](){ return 2*i; };
std::cout << f_ref() << std::endl;

The capture specifications [=] and [&] indicate that all variables used within the lambda body are to be captured by value or reference, respectively.

In this post, I’ve introduced a simple (but not too useful) example of how C++11 lambda functions work. In a later post I plan on discussing further more advanced uses of capture specifications and discuss on potential “gotcha” when using lambda functions to capture class member variables.

Comments are closed.