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

问题描述 投票:2回答:2

我已经用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++ multithreading standard-library
2个回答
8
投票

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

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

2
投票

问题是在函数模板特化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
}
© www.soinside.com 2019 - 2024. All rights reserved.