我已经用operator()重载编写了一个类,我想把这个类像一个函数指针一样传递给线程,所以我将它放在线程中,如下所示。但是,它无法编译,我注意到ofstream是它失败的原因。为什么这是错的?
#include <thread>
#include <fstream>
using namespace std;
class dummy{
public :
dummy(){}
void operator()(){}
private:
ofstream file;
};
int main()
{
dummy dum;
thread t1(dum);
return 0;
}
因为删除了std::basic_ofstream
复制构造函数,请参阅here。因此,您的dummy
类复制构造函数也被隐式删除。您需要移动对象而不是复制它:
std::thread t1(std::move(dum));
问题是在函数模板特化std::thread::thread<dummy &, void>
的实例化中,你看到dummy
作为参考传递,它试图复制dummy
对象,包括ofstream
(无法复制)。你可以通过使用std::ref
实际上将dum
的引用复制到线程中来解决这个问题。
#include <iostream>
#include <fstream>
#include <thread>
class dummy {
std::ofstream file;
public:
dummy() {}
void operator()() { std::cout << "in thread\n"; }
};
int main() {
dummy dum;
std::thread t1(std::ref(dum));
t1.join(); // dont forget this
}