最近在学习C++,在C++中分配内存使用new,那么我们如何判断是否申请成功,是否和C语言的方式相同,通过判空呢?
在网上查找相关的资料,有人提到直接判空仍然是会有问题的,我特意写了下代码测试,代码如下:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char *p_test = NULL;
while (1)
{
p_test = NULL;
p_test = new char[1000000];
if (p_test == NULL)
{
cout << "new have some wrong" << endl;
return -1;
}
}
cout << "break while " << endl;
return 0;
}
在ubuntu上进行测试,出现以下的信息:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std:bad_alloc
Aborted(core dumped)
当将上面修改成:
while (1)
{
p_test = NULL;
try
{
p_test = new char[1000000];
}
catch(exception e)
{
cout << "new have some wrong:" << e.what() << endl;
return -1;
}
}
运行结果如下:new have some wrong: std::exception
上面的std::exception的信息即e.what()的信息是从哪来的,请注意上面标记的两个蓝色地方,
当我们将
catch(exception e)修改成catch(std::bad_alloc e)时,输出的信息就是std::bad_alloc。
比较下上面两处结果,第一种情况下压根就没有进入到 if 的判断逻辑里面,也就是说即使new失败了,也不返回NULL。
做C开发习惯了用 if 判空方式来进行判断内存是否正常分配,在C++也可以这么做,具体如下:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char *p_test = NULL;
while (1)
{
p_test = NULL;
p_test = new(nothrow) char[1000000];
if (p_test == NULL)
{
cout << "forbidden new throw, new have some wrong" << endl;
return -1;
}
}
cout << "break while " << endl;
return 0;
}
禁止new失败时抛出异常,运行结果如下:
forbidden new throw, new have some wrong