Monday, September 25, 2017

C++14: Lambda capture expressions

C++14 added lambda capture expressions, which are mainly used to allow moves in lambda function parameters. Here is an example:

#include <iostream>
#include <memory>
#include <utility>

int main()
{
  std::unique_ptr<int> pInt{new int(9)};

  std::cout << pInt.get() << " ";

  auto myLambda = [lambda_ptr = std::move(pInt)]()
                  {
                    std::cout << lambda_ptr.get() << " ";
                  };

  myLambda();

  std::cout << pInt.get() << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 003B9E90 003B9E90 00000000
Reference: https://en.wikipedia.org/wiki/C%2B%2B14#Lambda_capture_expressions

No comments:

Post a Comment