【问题标题】:Moving std::thread移动 std::thread
【发布时间】:2013-07-14 11:50:03
【问题描述】:

尝试制作简单的代码工作:

std::thread threadFoo;

std::thread&& threadBar = std::thread(threadFunction);

threadFoo = threadBar; // thread& operator=( thread&& other ); expected to be called

得到一个错误:

使用已删除函数'std::thread& std::thread::operator=(const std::thread&)'

我明确地将threadBar 定义为右值引用,而不是普通的。为什么没有调用预期的运算符?如何将一个线程移到另一个线程?

谢谢!

【问题讨论】:

    标签: c++ multithreading c++11 move-semantics assignment-operator


    【解决方案1】:

    命名引用是左值。左值不绑定到右值引用。您需要使用std::move

    threadFoo = std::move(threadBar);
    

    【讨论】:

    • 感谢您的回答。我是否正确地认为可以使用预期运算符的一种(也是唯一?)方式是使用像threadFoo = std::thread(threadFunction); 这样的临时线程对象?
    • std::move 获得的临时参考或未命名参考。
    • 感谢您的解释!
    【解决方案2】:

    另见std::thread::swap。这可以实现为

    std::thread threadFoo;
    std::thread threadBar = std::thread(threadFunction);
    threadBar.swap(threadFoo);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-18
      • 2012-03-05
      • 2012-09-25
      • 1970-01-01
      • 2013-11-26
      • 2012-04-17
      • 1970-01-01
      • 2020-12-15
      相关资源
      最近更新 更多