带有 unique_ptr 和线程的默认向量构造函数

Default vector constructor with a unique_ptr and thread

调用创建 std::unique_ptr 持有线程的 'n' 个元素的默认向量构造函数的正确方法是什么。

std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::make_unique<std::thread>(std::thread(), threadWorker)));

std::vector<std::unique_ptr<std::thread>> thr_grp(5, std::move(std::unique_ptr<std::thread>(new std::thread(threadWorker))));

或者没有 std::move 语义?

这不能以这种方式完成,因为 std::vector 的 fill constructors 复制了指定的参数,而 std::unique_ptr 删除了复制构造函数。

您可以 emplace 元素到默认构造的 std::vector<std::unique_ptr<std::thread>> 中,如下例所示:

#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;
}

另一种方法是使用默认构造值构建和填充您的 std::vector,然后再分配这些值:

std::vector<std::unique_ptr<std::thread>> thr_grp(5);
for(auto& e : thr_grp)
    e = std::make_unique<std::thread>(threadWorker);

上面的代码将使用移动语义,您不必用 std::move.

明确指示它