首页 > 解决方案 > 将只移动函数参数传递给 boost::thread 构造函数

问题描述

以下适用于std::thread. 它打印 10 作为输出,这是我想要的。

void foo(std::unique_ptr<int> && in) {
  std::cout << *in;
}

int main(){
  auto in = std::make_unique<int>(10);
  std::thread t(foo, std::move(in));
  t.join();
} 

但是,使用 Boost 1.72 的类似尝试无法编译

void foo(std::unique_ptr<int> && in) {
    std::cout << *in;
}

int main(){

    auto in = std::make_unique<int>(10);
    boost::thread t(foo, std::move(in));
    t.join();
} 
Error : note: copy constructor of 'list1<boost::_bi::value<std::unique_ptr<int>>>' is implicitly deleted because base class 'storage1<boost::_bi::value<std::unique_ptr<int>>>' has a deleted copy constructor
template< class A1 > class list1: private storage1< A1 >

我觉得这很令人惊讶,因为 boost::thread 的文档说明了以下内容:

带参数的线程构造函数模板 <class F,class A1,class A2,...> thread(F f,A1 a1,A2 a2,...);

前提条件:F 和每个 An 必须是可复制的或可移动的。

由于我传递了 astd::unique_ptr作为论点,因此我满足了“可移动”标准。所以,我想知道为什么 boost 线程要构建std::unique_ptr? 它不应该将 std::unique_ptr 移动到线程对象中,然后像实现那样将其进一步移动到线程函数std::thread中吗?

标签: c++multithreadingc++11boostboost-thread

解决方案


根据文档,boost::thread以完全相同的方式使用参数boost::bind,并且函数和参数的这种组合不适合boost::bind(并且std::bind就此而言)。

std::bind(foo, std::move(in))(); // error
boost::bind(foo, std::move(in))(); // error

std::threadstd::bind或更健壮boost::bind

如果您需要将参数移动到foo,则需要将其包装在一个函数或 lambda 中,该函数或 lambda 通过非常量左值引用接受它并将其移动到foo. 否则,只需更改foo为接受非常量左值引用参数。


推荐阅读