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

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

#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 ;
    }
}


你可能感兴趣的:(使用智能指针安全释放资源)