Default vector constructor with unique_ptr and stream
What is the correct way to call the default vector constructor that creates "n" elements std::unique_ptr
containing streams.
std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::make_unique<std::thread>(std::thread(), threadWorker)));
or
std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::unique_ptr<std::thread>(new std::thread(threadWorker))));
or with semantics std::move
?
source to share
It cannot be done this way, because the constructors are populated std::vector
to make copies of the specified parameter, and the std::unique_ptr
remote copy instance is.
You can emplace elements in the default built std::vector<std::unique_ptr<std::thread>>
, as shown in the following example:
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
void threadWorker() {
std::cout << "I'm thread: " << std::this_thread::get_id() << std::endl;
}
int main() {
std::vector<std::unique_ptr<std::thread>> thr_grp;
for(int i = 0; i < 5; ++i)
thr_grp.emplace_back(std::make_unique<std::thread>(threadWorker));
for(auto& e : thr_grp)
e->join();
return 0;
}
Another approach is to create and populate std::vector
default configured values ββand assign values ββlater:
std::vector<std::unique_ptr<std::thread>> thr_grp(5);
for(auto& e : thr_grp)
e = std::make_unique<std::thread>(threadWorker);
The above code will use move semantics, you don't need to explicitly specify it with std::move
.
source to share