new失败判断-创新互联
使用 malloc/calloc 等分配内存的函数时,一定要检查其返回值是否为空;
但是C++ 里,如果 new 分配内存失败,默认是抛出bad_alloc异常,不会返回空;
但是有些编译器对c++标准支持不是很好,比如vc++6.0中new失败不会抛出异常,而返回0。
分享标题:new失败判断-创新互联
文章来源:http://scyanting.com/article/dgjhgi.html
但是C++ 里,如果 new 分配内存失败,默认是抛出bad_alloc异常,不会返回空;
但是有些编译器对c++标准支持不是很好,比如vc++6.0中new失败不会抛出异常,而返回0。

INT*p = NULL;
try
{
p = new INT[size];
if(NULL == p)
{
return FALSE;
}
}
catch (std::bad_alloc& ba)
{
std::cerr << "bad_alloc caught: " << ba.what() << '
';
}
方案二:标准 C++ 亦提供了一个方法来抑制 new 抛出异常,而返回空指针。
INT* p = new (std::nothrow) INT[size];
if(NULL == p)//此时判空就有意义了{
return FALSE;
}
分享标题:new失败判断-创新互联
文章来源:http://scyanting.com/article/dgjhgi.html