【发布时间】:2015-08-23 21:56:33
【问题描述】:
我正在关注有关线程的在线教程并收到错误消息“语义问题:尝试使用已删除的函数”。知道有什么问题吗?
#include <iostream>
#include <thread>
#include <string>
using namespace std;
class Fctor {
public:
void operator() (string & msg) {
cout << "t1 says: " << msg << endl;
msg = "msg updated";
}
};
int main(int argc, const char * argv[]) {
string s = "testing string " ;
thread t1( (Fctor()), s);
t1.join();
return 0;
}
【问题讨论】:
-
完整的错误是什么?
-
Fctor() 构造的对象寿命不够长,无法在线程中使用。
-
@bmargulies 不,没关系。这是另一个参数
s的问题。我猜std::ref(s)会起作用。 -
我看到的第一个问题是尝试将对象作为左值传递给函子,但
std::thread将左值到右值的转换应用于参数的类型,因此调用将失败,因为它不会传递左值。尝试用std::reference_wrapper(thread t1(Fctor(), std::ref(s))) 包裹它
标签: c++ multithreading