使用unique_ptr和thread的默认向量构造函数

3

如何正确调用默认的向量构造函数,以创建包含线程的'n'个std::unique_ptr元素。

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语义呢?

1个回答

6
这种做法行不通,因为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来指示它。

1
我通常更喜欢第二个。 - MikeMB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接