C++11 std::thread std::move 抱怨尝试使用已删除的函数

kww*_*kww 5 c++ multithreading c++11

我正在学习 C++11 线程并尝试编写一个更改共享内存的线程。我分别用了std::refstd::move。我使用以下命令运行代码g++ eg3.cpp -std=c++11 -pthread:但我发现std::move在我的 mac 上不起作用。我收到这样的错误:

In file included from eg3.cpp:1: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:337:5: error: 
      attempt to use a deleted function
    __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
    ^
...
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

#include<thread>
#include<iostream>
#include<mutex>
#include<condition_variable>
#include<string>
#include<functional>
#include<utility>
using namespace std;
int main(){
  string s = "Hello!";
  cout << "Main before: " << s << endl;
  // thread t([](string& s){cout << s << endl; s = "Ni hao!";}, ref(s)); //// This works!
  // thread t([](string& s){cout << s << endl; s = "Ni hao!";}, move(s)); //// This does not work
  t.join();
  cout << "Main after: " << s << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bry*_*hen 2

您只需使 lambda 采用string(按值)或string const &(按常量引用)或string &&(右值引用)即可支持移动。在这种情况下,因为您正在修改s,并且无法使用string const &.

thread t([](string && s){cout << s << endl; s = "Ni hao!";}, move(s));
Run Code Online (Sandbox Code Playgroud)

它失败了,因为您无法将右值引用 ( string &&) 传递给采用左值引用 ( ) 的函数/lambda string &

一个简化的例子是

void test(std::string &) {}
void test2(std::string &&) {}
void test3(std::string const&) {}
void test4(std::string) {}

int main(){
  std::string s;
  test(std::move(s)); // fail
  test2(std::move(s)); // ok
  test3(std::move(s)); // ok
  test4(std::move(s)); // ok
}
Run Code Online (Sandbox Code Playgroud)