C++11 lambdas

Today I played around with some of the C++11 features and stumbled across a small pitfall one could easily fall in when using lambdas. Lambdas are actually pretty cool and it's about time they are available in C++. You now can basically define an anonymous function where you need one.

#include <iostream>

int main(int argc, char **argv)
{
  auto bar = []{ std::cout << "Moo!" << std::endl; };
  bar();
}

We define an anonymous function which prints Moo! to stdout and call it with bar();.

You can also capture variables and use them inside your lambda. Capturing can be done by value or by reference.

#include <iostream>

int main(int argc, char **argv)
{
  int foo = 23;
  auto bar = [&foo]{ foo = 42; };
  auto baz = [ foo]{ std::cout << foo << std::endl; };

  bar();
  baz();
}

foo is initially set to 23. We call bar() which did capture foo by reference and set foo to 42. Then baz() is called which did capture foo by value. By value means it has a copy of foo (which is const btw). So what do you think baz() will print to stdout? 23 or 42?

Since that's the pitfall I talked about: it prints 23. Because baz() captured the value of foo when the lambda was defined and at this time foo was still 23. We didn't call bar() before we defined baz().

April 23, 2013 | c++11
about | blog | archives