在寫程序的時候,經常要做一步就要判斷這一步是否成功,如果不成功,則程序不能繼續往下走了,得刪除當前申請的資源。
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;
}