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
原创粉丝点击