boost之scope_exit

boost之scope_exit

在写程序的时候,经常要做一步就要判断这一步是否成功,如果不成功,则程序不能继续往下走了,得删除当前申请的资源。
void Fun()
{
     int * p =  new  int;
     if( error )
    {
        delete p;
         return;
    }

     float * p1 =  new  float;
     if( error1 )
    {
        delete p;
        delete p1;
         return;
    }
     .......
     .......
}
检查是否发生错误与删除资源的代码会越来越多,看上去十分之臃肿,boost提供了一个socp_exit,可以帮助我们解决上面之困。
void Fun()
{
     int * pInt =  new  int;
     float * pFloat =  new  float;
    BOOST_SCOPE_EXIT( (&pInt) (&pFloat) ) // 以引用的形式进行变量捕获
    {
        delete pInt;
        pInt = nullptr;
        delete pFloat;
        pFloat = nullptr;
        std::cout << __FUNCTION__ << std::endl;
    }
    BOOST_SCOPE_EXIT_END;
    
    
    std:: string str("abc");
    BOOST_SCOPE_EXIT( str )     // 以值传递的形式进行变量捕获
    {
        str = "123";
        std::cout << __FUNCTION__ << std::endl;
    }
    BOOST_SCOPE_EXIT_END

     return;
}




你可能感兴趣的:(boost之scope_exit)