关于boost::bind中fstream对象禁止拷贝的解决方法

来源:互联网 发布:风险管理矩阵 编辑:程序博客网 时间:2024/05/01 05:37

fstream的拷贝构造函数是私有的,禁止fstream对象的拷贝。

比如,下面的程序编译出错,提示拷贝构造函数私有:

#include<fstream>#include<iostream>#include<boost/thread/thread.hpp>using namespace std;void fun(ofstream &out){std::cout<<"succeed!"<<endl;}int main(){ofstream coutt("a.txt");fun(coutt);boost::bind(&fun,coutt);}

编译结果:


在上述代码中,如果将coutt参数改为其他的非对象参数或者自己定义的对象都不会发生这个问题。
解决办法是用std::ref(或者boost::ref)将fstream对象包装。改过后的代码如下:

#include<fstream>#include<iostream>#include<boost/thread/thread.hpp>#include<boost/bind.hpp>using namespace std;void fun(ofstream &out){std::cout<<"succeed!"<<endl;}int main(){ofstream coutt("a.txt");fun(coutt);boost::bind(&fun,boost::ref(coutt));}

再次编译,可以通过。

注意:使用std::ref需要包含头文件#include<functional>


std::ref 用于包装按引用传递的值。

std::cref 用于包装按const 引用传递的值。

参考:http://www.cppblog.com/everett/archive/2012/12/03/195939.html


0 0