使用智能指针安全释放资源
#include <stdio.h>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
using namespace boost;
void testreadfile()
{
FILE *p = fopen("a.txt", "w");
if(1)
{
//return;
}
fclose(p);
}
void closefile(FILE *p)
{
fclose(p);
}
void testreadfilesp()
{
FILE *p = fopen("a.txt", "w");
shared_ptr<FILE> sp(p, boost::bind(closefile, p));
if(1)
{
return;
}
}
int main()
{
testreadfile();
testreadfilesp();
return 0;
}
延伸使用smart_ptr来执行程序退出前需要清理的东东
void functionneedstowhenover(int x, int y)
{
std::cout<<"x: "<<x<<"y: "<<y<<"\n";
}
void testfunctionover(int a, int b)
{
shared_ptr<void> spcode( static_cast<void*>(0), boost::bind(functionneedstowhenover, b, a));
if( a < b)
{
std::cout<<"a is little than b"<<"\n";
return ;
}
}
posted on 2014-07-04 14:27
pizzx 阅读(311)
评论(0) 编辑 收藏 引用 所属分类:
c++/boost