一标题
关于goto语句,我们都知道是不推荐使用的,会造成程序结构不清晰,最近觉得突然发现“存在即合理”,其实也不会很混乱,相反,运用得当省事多了。
比如在下面的代码,当我们需要去new多个对象时(代码简写了),需要多次判空,针对每一次的new失败,都需要delete之前的对象,就显得罗里吧嗦。
二 代码
#include <iostream>
using namespace std;
bool IsRight()
{
bool bok =false;
int * pInt = new (std::nothrow)int(5);
char * pChar = new (std::nothrow)char('c');
double * pDouble = new (std::nothrow)double(3.12);
if(pInt == NULL)
{
goto EXIT;
}
if(pChar == NULL)
{
goto EXIT;
}
if(pDouble == NULL)
{
goto EXIT;
}
std::cout<<*pInt<<std::endl;
std::cout<<*pChar<<std::endl;
std::cout<<*pDouble<<std::endl;
bok = true;
goto EXIT;
EXIT:
if(pInt != NULL)
{
delete pInt;
}
if(pChar != NULL)
{
delete pChar;
}
if(pDouble != NULL)
{
delete pDouble;
}
return bok;
}
int main()
{
IsRight();
return 0;
}
算是不能因噎废食吧