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




posted on 2013-07-15 17:30 永遇乐 阅读(2067) 评论(0)  编辑 收藏 引用 所属分类: STL & Boost


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


<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(6)

随笔分类

推荐Blog

友情链接

搜索

最新评论

阅读排行榜