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

简介:

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


目录
相关文章
|
4月前
|
编译器 C++
02头文件的冲突导致,清除缓冲区失败之cin.ignore() 问题
输入任意多个整数, 把这些数据保存到文件data.txt中. 如果在输入的过程中, 输入错误, 则提示用户重新输入. 指导用户输入结束(按ctrl + z) [每行最多保存4个整数] 可能遇到的 cin.ignore();问题
46 0
|
3月前
|
编译器 C语言 C++
C++中.h和.hpp文件有什么区别?
C++中.h和.hpp文件有什么区别?
|
11月前
|
编译器
引用头文件的操作
引用头文件的操作。
35 0
|
9月前
|
Linux 编译器 C语言
Linux环境下gcc编译过程中找不到名为pthread_create的函数的定义:undefined reference to `pthread_create‘
Linux环境下gcc编译过程中找不到名为pthread_create的函数的定义:undefined reference to `pthread_create‘
106 0
解决办法:对‘operator delete(void*)’未定义的引用
解决办法:对‘operator delete(void*)’未定义的引用
168 0
关于 error: C2039: “shared_ptr”: 不是“std”的成员 的解决方法
关于 error: C2039: “shared_ptr”: 不是“std”的成员 的解决方法
关于 error: C2039: “shared_ptr”: 不是“std”的成员 的解决方法
ThinkPHP5使用include多次引入文件传入变量问题
ThinkPHP5使用include多次引入文件传入变量问题
262 0
|
JSON 数据格式 Python
.NET6新东西--隐式命名空间引用
.NET6新东西--隐式命名空间引用
314 0
.NET6新东西--隐式命名空间引用