How to place futures in a container?

I am trying to put futures created asynchronously in a vector, so I don't need to do something like:

auto f1 = async(....); auto f2 = async(....); ... f1.get(); f2.get(); ... 

The compilation error that I get with this code is "Calling the remote constructor" std :: _ 1 :: future ". Can someone help me how to do this correctly. Not sure if I copy the future to the vector .

 void AudioAnalyzer::retrieve() { deque<shared_ptr<AudioAnalysis>>tempData(data); vector<future<void>> futures; for (int i = 0; i < NUM_THREADS; ++i) { auto f = async(bind(&AudioAnalyzer::analysisThread, this, _1), ref(tempData)); futures.push_back(f); } for (auto& f : futures) { f.get(); } } void AudioAnalyzer::analysisThread(deque<shared_ptr<AudioAnalysis>>& aq ) { while (true) { m.lock(); if (aq.size() == 0) { m.unlock(); break; } auto aa = aq.front(); aq.pop_front(); m.unlock(); if (false) //testing { retrieveFromDb(aa); } else { analyzeAudio(aa); } } } 
+6
source share
2 answers

Futures cannot be copied, but they are copied with the ability to move. You need to move them to the container:

 futures.push_back(std::move(f)); 

Here std::move(f) looks like an rvalue, as a result of which the overload std::vector<future<void>>::push_back is selected.

+10
source

If you are using C ++ 11, you can also use the new emplace_back operator std :: vector as follows:

 futures.emplace_back(std::async(std::launch::async, f)); 

This will create a std::future object in place (directly in std :: vector) and thus there will be no need to copy or move the future.

See http://en.cppreference.com/w/cpp/container/vector/emplace_back

+6
source

All Articles