Storing a future in a list

2020-06-03 02:22发布

I want to store the futures of several threads spawned using async in a list to retrieve their results later.

future<int> f = async(doLater, parameter);
list<future<int>> l;
l.push_back(f);

However the compiler prints the following error message

/usr/include/c++/4.7/bits/stl_list.h:115:71: error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = int; std::future<_Res> = std::future]'

Am i doing something wrong or aren't lists supposed to store futures? If they are not, what to use instead?

1条回答
对你真心纯属浪费
2楼-- · 2020-06-03 02:36

std::future is not copyable - you need to move into the list. Either:

future<int> f = async(doLater, parameter);
list<future<int>> l;
l.push_back(std::move(f));

or:

list<future<int>> l;
l.push_back(async(doLater, parameter));

will work, with the latter being preferable since it doesn't leave a moved-from object littering the scope.

查看更多
登录 后发表回答