首页 > 解决方案 > 为什么ofstream作为类成员不能传递给线程?

问题描述

我写了一个带有 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;
}

标签: c++multithreadingstandard-library

解决方案


因为std::basic_ofstream复制构造函数被删除了,看这里。因此,您的dummy类复制构造函数也被隐式删除。您需要移动对象而不是复制它:

std::thread t1(std::move(dum));

推荐阅读