Another Alternative to Lambda Move Capture -- John Bandela

[Ed.: John Bandela correctly points out some hazards of one approach to capture-by-move in C++11 lambdas. In this blog post, he offers his own safer solution.]

Another Alternative to Lambda Move Capture

by John Bandela

Today the post on isocpp.org called Learn How to Capture By Move caught my attention. I found the post informative and thought provoking, and you should go and read it before reading the rest of this post.

The problem is how do we lambda capture a large object we want to avoid copying?

The motivating example is below:

function<void()> CreateLambda()  
{  
  vector<HugeObject> hugeObj;  
  // ...preparation of hugeObj...  
  auto toReturn = [hugeObj] { /*...operate on hugeObj...*/ };  
  return toReturn;  
}

The solution proposed is a template class move_on_copy that is used like this:

auto moved = make_move_on_copy(move(hugeObj));
auto toExec = [moved] { /*...operate on moved.value...*/ };

However, there are problems with this approach, mainly in safety. The move_on_copy acts as auto_ptr and silently performs moves instead of copies (by design).

I present here a different take on the problem which accomplishes much of the above safely, however, with a little more verbosity in exchange for more clarity and safety.

Continue reading...

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.