仅移动类型的back_inserter

back_inserter for move-only type

本文关键字:inserter back 移动 类型      更新时间:2023-10-16

在下面的代码中,对象'queue'是不可复制的,但由于std::互斥,它是可移动的。

std::generate_n(std::back_inserter(thread_pool),
                std::thread::hardware_concurrency,
                [&](){return std::thread(handler(), exiting, queue);});

VC++2012无法编译,因为互斥对象上有一个私有副本构造函数。它无法为队列生成复制构造函数。为什么会有任何东西试图复制队列?在我看来,一切都是参考的,因此没有副本。

正试图通过将值传递给std::thread构造函数来复制queue。如果要传递引用,请使用包装器:std::ref(queue)

如果您真的想将queue移动到std::thread中,则需要传递std::move(queue)使其成为右值。不过,由于VS中的一个错误,它仍然无法工作。