Lambdas Capture Lists

Give access to variables that are outside of the scope of the lambda.


  double a{10};
  double b{20};

  auto func = [a, b]() { std::cout << "a + b : " << a + b << std::endl; };
  func();

  • Capturing by value: what we have in the lambda function is a copy
  
  // incrementation doesn't affect inner value

  int c{42};

  auto func = [c]() { std::cout << "inner value: " << c << std::endl; };

  for (size_t i{}; i < 5; ++i) {
    std::cout << "outer value: " << c << std::endl;
    func();
    ++c;
  }

  • Capturing by reference: working on the original outside value
  
  // incrementation affects inner value

  int c{42};

  auto func = [&c]() { std::cout << "inner value: " << c << std::endl; };

  for (size_t i{}; i < 5; ++i) {
    std::cout << "outer value: " << c << std::endl;
    func();
    ++c;
  }