Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default vector constructor with a unique_ptr and thread

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?

like image 587
Theko Lekena Avatar asked Nov 21 '25 05:11

Theko Lekena


1 Answers

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.

like image 143
Akira Avatar answered Nov 22 '25 18:11

Akira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!