【问题标题】:Why is ofstream as a class member can not be passed to thread?为什么ofstream作为类成员不能传递给线程?
【发布时间】:2019-09-02 23:22:15
【问题描述】:

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

【问题讨论】:

  • 错误信息是什么?
  • 打赌这与尝试复制 iostream 对象有关。

标签: c++ multithreading standard-library


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    问题出在函数模板特化std::thread::thread&lt;dummy &amp;, void&gt; 的实例化中,您看到dummy 作为引用传递,它试图复制dummy 对象,包括ofstream(不能复制)。您可以通过使用std::refdum 的引用实际复制到线程中来解决此问题。

    #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
    }
    

    【讨论】:

    • 注意,如果在 main() 中没有使用它并且 dum 超出范围,那么你就有麻烦了。我更喜欢搬家。
    • 当然,dummy 实例必须比线程寿命更长,因此join() 必须在dummy 超出范围之前完成。哪个更可取取决于情况。 dummy 可以由在join 等之后可用的线程填充结果,而我认为通过引用传递它会更好。
    猜你喜欢
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 2021-10-20
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多