随笔 - 21  文章 - 0  trackbacks - 0
<2014年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

常用链接

留言簿

随笔分类

随笔档案

文章分类

搜索

  •  

最新评论

阅读排行榜

评论排行榜

使用智能指针安全释放资源

#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 阅读(298) 评论(0)  编辑 收藏 引用 所属分类: c++/boost

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理