【问题标题】:boost::thread and std::unique_ptrboost::thread 和 std::unique_ptr
【发布时间】:2011-06-18 19:35:58
【问题描述】:

是否有可能将 std::unique_ptr 作为参数传递给 boost::thread 构造函数?如果不是,最好的解决方法是什么?

一个小例子:

// errors: g++ uniqueptr_thread.cpp -std=c++0x

#include <iostream>
#include <memory>
#include <boost/thread.hpp>

class TestThread{
public:
  void operator()(std::unique_ptr<int> val){
    std::cout << "parameter: " << val << std::endl;
  }

};

int main(int argc, char* argv[]){

  std::unique_ptr<int> ptr(new int(5));

  boost::thread th( new TestThread(), std::move(ptr));

}

【问题讨论】:

    标签: c++ multithreading boost c++11


    【解决方案1】:

    这为我编译和运行:

    #include <iostream>
    #include <memory>
    #include <thread>
    
    class TestThread{
    public:
      void operator()(std::unique_ptr<int> val){
        std::cout << "parameter: " << *val << std::endl;
      }
    };
    
    int main()
    {
    
      std::unique_ptr<int> ptr(new int(5));
    
      std::thread th( TestThread(), std::move(ptr));
      th.join();
    
    }
    

    但它必须处于 C++0x 模式。我不知道提升移动仿真是否足以做到这一点。

    【讨论】:

    • 使用哪个编译器? g++ 4.4.5 给了我比 boost 版本更长的错误列表,使用相同的选项 (-std=c++0x)
    • @Dutwo:根据 C++0x,它应该可以工作。如果没有,那么您的 GCC 或 libc++ 版本可能有问题。也许试试更新的?
    • 我在 Mac OS X 上使用了 clang + libc++ (llvm.org),非常接近它们的开发主干。
    • 这也不能在 GCC4.6 中编译。目前我天真的猜测是因为std::bind 删除了引用,并且没有右值引用包装器。事实上,使用 make_adv 构造 from this SO question 我可以让它编译,但我在运行时得到一个 system_error 异常。
    • VS2013构建失败
    【解决方案2】:

    一个std::unique_ptr,顾名思义,是unique只能有一个!

    现在,如果您的线程函数采用 std::unique_ptr&&,并且您使用 std::move 移动线程函数中的参数,那么您可以传递 std::unique_ptr。但是你的副本将是空的,因为你把它移到了另一个线程。

    如果 std::move 不起作用,那么您的编译器或标准库中可能存在错误。我想像这样跨线程转移所有权并不常见。而且 C++11 还是相当新的。

    【讨论】:

    • +1。我怀疑将它移到另一个线程是他想要的。这看起来像是一种将任意对象传递给线程的干净方法。
    • 对不起,我忘记了示例代码中的 std::move,它在原始代码中,但它仍然无法编译
    【解决方案3】:

    您确定您的问题出在 unique_ptr 上吗?为什么你的例子使用 new 来创建你的仿函数?那一行应该是:

    boost::thread th(TestThread(), std::move(ptr));
    

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2020-12-21
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多