为什么ofstream作为类成员不能传递给线程
Why is ofstream as a class member can not be passed to thread?
我写了一个带有运算符((重载的类,我想像函数指针一样传递这个类到线程,所以我把它放在线程中,如下所示。但是,它无法编译,我注意到 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
}
相关文章:
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 为什么线程不接受此输入?
- C++ 中的线程不能使用参数
- ASIO signal_set多个 IO 线程不可靠,具体取决于代码顺序?
- C++线程不检测全局变量更改
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 线程不是 std c++ 的成员
- 运行 std::线程不在构造函数中
- 为什么我的线程不在后台运行?
- STD ::线程不会退出
- 特征中的多线程(不使用 OpenMP)
- C++11 线程不以 SDL 结尾
- 线程不在 Linux 上终止,但在 Mac 上终止
- 为什么 omp 并行部分中的线程不会在其部分上划分?
- 多线程不像预期的那样行动
- 使用优化标志进行编译时线程不启动
- 为什么VS2017协程不能返回无效?
- 串口读取功能的通信超时和线程不超时
- C 11中的线程不在类成员中
- 为什么我的线程不能优雅地退出?