Capture-by-Move for lambdas in C++

Marco Arena looks at how to implement move semantics for lambda captures – useful if you wish to capture a large object without using shared_ptr (perhaps to avoid other parties mutating the object outside the lambda).

John Bandela proposed an alternative approach.

All very interesting, but as the comments suggest, it’s best to introduce an extra parameter to the lambda and use std::bind:

function CreateLambda()
{
  std::vector<Huge> hugeObj;
  // ...preparation of hugeObj...

  auto toReturn = std::bind(
    [](std::vector<Huge>& hugeObj)
    { /*..operate on hugeObj..*/ },
    std::move(hugeObj));

  return toReturn;
}

Leave a comment

Filed under C++

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.