在C++中除非请求分配的内存量特大,或系统处于临界状态,可供使用的内存很少,new 一般都能成功。
有些应用程序需要请求分配大块的内存(如数据库应用程序), 一般而言,不要假定内存分配能够成
功,这很重要。C++提供了两种确保指针有效的方法,默认方法是使用异常,即如果内存分配失败,将引发std::bad alloc 异常。这导致应用程序中断执行,除非您提供了异常处理程序,否则应用程序将崩溃,并显示一条类似于“异常未处理”的消息。另外一种方法是使用C++提供的new(nothrow)关键字进行内存分配,但是new(nothrow)不会引发异常,会直接返回NULL,这样在使用指针之前只需要检查其有效性即可。
代码示例:
#include <iostream>
using namespace std ;
int main()
{
try
// Request lots of memory space
int* pAge = new int [ 536870911] ;
// Use the allocated memory
delete[] pAge;
catch (bad_ alloc)
{
cout << "Memory allocation failed. Ending program" << endl;
}
return 0;
}
上述代码运行输出:Memory allocation failed. Ending program
使用new(nothrow)关键字进行内存分配。
#include <iostream>
using namespace std;
int main()
{
// Request lots of memory space, use nothrow version
int* pAge = new(nothrow) int [0x1fffffff];
if (pAge) // check pAge != NULL
{
// Use the allocated memory
delete[] pAge;
}
else
cout << "Memory allocation failed. Ending program" << endl;
return 0;
}