C++ 移动std::线程
尝试让简单的代码工作:C++ 移动std::线程,c++,multithreading,c++11,move-semantics,assignment-operator,C++,Multithreading,C++11,Move Semantics,Assignment Operator,尝试让简单的代码工作: 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 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
定义为右值引用,而不是普通引用。为什么不调用预期的运算符?如何将一个线程移动到另一个线程
谢谢大家! 命名的引用是左值。左值不绑定到右值引用。您需要使用
std::move
threadFoo = std::move(threadBar);
另见。这可以按如下方式实施:
std::thread threadFoo;
std::thread threadBar = std::thread(threadFunction);
threadBar.swap(threadFoo);
谢谢你的回答。使用预期运算符的唯一方法是使用像
threadFoo=std::thread(threadFunction)这样的临时线程对象,这对我来说正确吗代码>?从std::move
获得的临时或未命名引用。感谢您的解释!