fstream对象作为函数参数的问题汇总及解决方法
来源:互联网 发布:手游代练软件 编辑:程序博客网 时间:2024/04/30 22:19
今天想写一个多线程读取一个文本文件,需要fstream对象作为函数参数,出现了编译错误,查询了网上很多资料,在此汇总一下。
<span style="font-size:18px;">#include <boost/thread/thread.hpp>#include <boost/atomic.hpp>#include <iostream>#include <time.h>#include <string>#include <boost/bind.hpp>#include <fstream>using namespace std;boost::mutex mt;void Print(fstream fr){string sth;mt.lock();getline(fr, sth);cout << sth << endl;mt.unlock();}int main(){fstream fr;fr.open("E:\\test\\theap\\image.txt", ios_base::in);Print(fr);th1.join();th2.join();return 0;}</span>上面的代码编译出错。原因就是fstream 对象没有复制构造函数,因此不能执行复制操作,而函数是实参复制给形参,因此这里就出错。因此,我们必须使用引用的方式传递参数。
子函数修改为:
<span style="font-size:18px;">void Print(fstream& fr)// 此处必须使用引用方式传递参数{string sth;mt.lock();getline(fr, sth);cout << sth << endl;mt.unlock();}</span>
这样修改后,普通调用就没有问题了!
修改后的完整代码:
<span style="font-size:18px;">#include <boost/thread/thread.hpp>#include <boost/atomic.hpp>#include <iostream>#include <time.h>#include <string>#include <boost/bind.hpp>#include <fstream>using namespace std;boost::mutex mt;void Print(fstream& fr){string sth;mt.lock();getline(fr, sth);cout << sth << endl;mt.unlock();}int main(){fstream fr;fr.open("E:\\test\\theap\\image.txt", ios_base::in);//Print(fr);boost::thread th1(boost::bind(Print, fr));boost::thread th2(boost::bind(Print, fr));th1.join();th2.join();return 0;}</span>我使用了boost::bind(Print,fr),这里又报错了。具体可参考:http://blog.csdn.net/yuan1164345228/article/details/49176029
解决方法就是,使用用std::ref(或者boost::ref)将fstream对象包装。
std::ref 用于包装按引用传递的值。
std::cref 用于包装按const 引用传递的值。
修改两行代码:boost::thread th1(boost::bind(Print, boost::ref(fr)));boost::thread th2(boost::bind(Print, boost::ref(fr)));
0 0
- fstream对象作为函数参数的问题汇总及解决方法
- C++中关于将fstream对象作为函数参数传递相关问题说明
- 关于 fstream 类型作为参数传递的问题
- fstream引用作为函数返回值问题
- 对象作为函数参数
- 对象作为函数参数
- CPen 对象不能作为函数的参数
- 对象作为参数传递的相关问题
- 类对象及类成员函数作为函数参数的方法
- 指针作为函数参数的问题
- Django model作为函数参数的问题
- 指针作为函数参数的问题
- C++指针作为函数参数的问题
- 数组作为函数参数的指针问题
- 指针作为函数参数传递的问题
- C++对象作为函数参数
- c++对象作为函数参数
- 类对象作为函数参数
- Objective-C Runtime 运行时之四:Method Swizzling
- 这些Tips让你的App更容易维护
- 将彩色图片转化为灰度图
- php.ini 的一点问题
- 将流信息转化成字符串
- fstream对象作为函数参数的问题汇总及解决方法
- hdu 4715 Difference Between Primes【筛法快速求素数表+思维】
- CCF有趣的数(快速幂,递推)
- Objective-C Runtime 运行时之五:协议与分类
- Java中的WeakReference讲解
- PHP开源框架 CodeIgniter
- 第七周项目一 (成员函数,友元函数和一般函数的区别)
- sudo免密码
- cocos2d Label无法正常显示中文