Move-semantics and std :: future

I'm working on C ++ 11 features myself and recognize the move semantics and try to apply it to at least every function that handles containers or large objects. Now I have found some tasks that I would like to run in parallel, so I would use a std :: future, but these tasks handle containers (in my situation, they return a container). So I have this pseudocode:

std::future<container&&> c = std::async([]()->container&&{ /* stuff return a local container object */ });

      

And know I am asking myself, how is the lifetime control of an rval ref container? If I am correct and the task is completed before I call c.get () it will be saved. Will the stored value still contain the usable object?

Does this provide a lifespan?

std::future<container> c = std::async([]()->container&&{ /* same stuff -- ^ -- */ });
container cc = std::move(c.get());

      

+3


source to share


1 answer


It looks like you are using move semantics incorrectly.

You must return by value, not by reference rvalue, and let the move constructor ensure that return by value is efficient. Otherwise, you risk returning a dangling reference to an object that no longer exists. The semantics of the move point is to make transfer objects cheap, rvalue references are just a language feature that allows this, don't use rvalue references by themselves.

In other words, you want to move data from the lambda body, to the return value of the lambda, to a future stored value. This one moves data . You don't want to pass a reference that moves nothing (and you can already pass things by reference in C ++ 03 using lvalue references!)

Your lambda should return by value, but future

should store by value:



std::future<container> c = std::async([]()->container{ /* stuff */ });

      

And you don't need to use std::move

, unique futures return the stored value as an rvalue, so you can jump from it automatically without using std::move

to pass it to the rvalue:

container cc = c.get();   // cc will be move constructed

      

+5


source







All Articles