Initilize a vector of std future at construction

Viewed 41

Consider following code:

#include <vector>
#include <future>

using namespace std;

void someFunction(){

  //do something
}

int main() {

  vector<future<void>> tasks1;

  tasks1.emplace_back(async(launch::async, someFunction));
  
  vector<future<void>> tasks2{ async(launch::async, someFunction) }; //doesn't compile

  vector<future<void>> tasks3{ move(async(launch::async, someFunction)) }; //doesn't compile

}

Why doesn't task2 and task3 compile? I would assume that the move constructor is called in tasks3 but it is not.

1 Answers

future cannot be copied, only can be moved.

By

{ async(launch::async, someFunction) }

future is stored in initializer_list. All elements of initializer list are considered to be const, reference. const object as a source object can be only copied into the target vector, not moved, that is why the code compilation failed.

Related