What is the right way to call teh default vector contructor that creates 'n' elements of std::unique_ptr's holding threads.
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 either with out the std::move semantic?
This cannot be done in this way because fill constructors of the std::vector make copies of the specified parameter and the std::unique_ptr has deleted copy constructor.
You can emplace elements into a default constructed std::vector<std::unique_ptr<std::thread>> like the following example does:
#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 construct and fill your std::vector with default constructed values and assign the 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 code above will use move semantics, you don't have to explicitly indicate it with std::move.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With