Here is the test code presented using one of two options:
#include <vector> #include <future> #include <iostream> #include <algorithm> using namespace std; // option 1 : pass a reference to the future void test1() { vector<double> v = { 0, 1.1, 2.2, 3.3, 4.4, 5.5 }; auto K = [=](double z){ double y=0; for (const auto x : v) y += x*x*z; return y; }; vector<future<double>> VF; for (double i : {1,2,3,4,5,6,7,8,9}) VF.push_back(async(K,i)); for_each(VF.begin(), VF.end(), [](future<double>& x){cout << x.get() << " "; }); } // option 2 : store shared_futures which allow passing copies void test2() { vector<double> v = { 0, 1.1, 2.2, 3.3, 4.4, 5.5 }; auto K = [=](double z){ double y=0; for (const auto x : v) y += x*x*z; return y; }; vector<shared_future<double>> VF; for (double i : {1,2,3,4,5,6,7,8,9}) VF.push_back(async(K,i)); for_each(VF.begin(), VF.end(), [](shared_future<double> x){cout << x.get() << " "; }); }
source share