为什么ofstream作为类成员不能传递给线程

Why is ofstream as a class member can not be passed to thread?

本文关键字:线程 不能 成员 ofstream 为什么      更新时间:2023-10-16

我写了一个带有运算符((重载的类,我想像函数指针一样传递这个类到线程,所以我把它放在线程中,如下所示。但是,它无法编译,我注意到 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复制构造函数被删除了,所以请参阅此处。因此,您的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 threadn"; }
};
int main() {
    dummy dum;
    std::thread t1(std::ref(dum));
    t1.join(); // dont forget this
}