1. plain new/delete:
普通的new 定义如下:void *operator new(std::size_t) throw(std::bad_alloc);
void operator delete(void*) throw();
注意:标准C++ plain new 失败后抛出标准异常std::bad_alloc而非返回NULL,因此检查返回值是否为NULL判断分配内存空间是没有意义的
普通new申请空间示例代码:
#include <iostream>
using namespace std;
typedef unsigned long ULONGS;
char *GetMemory(ULONGS size);
int main()
{
try
{
ULONGS ulSize(10e11);
char *pMem=GetMemory(ulSize);
if(NULL == pMem)
{
cout<<"Alloc Memory failure!"<<endl;
}
delete [] pMem;
pMem = NULL;
}
catch(const std::bad_alloc &ex)
{
cout<<ex.what()<<endl;
}
return 0;
}
char *GetMemory(ULONGS size)
{
char * pMem = new char[size];//分配失败,指针不为空
if(NULL == pMem)
{
cout<<"Alloc Memory failure!"<<endl;
}
return pMem;
}
这段代码运行出来结果如下图所示:
代码抛出申请申请空间异常的信息
2.nothrow new/delete:
void *operator new(std::size_t,const std::nothrow_t&) throw();
void operator delete(void*) throw();
struct nothrow_t{}; const nothrow_t nothrow;//nothrow作为new的标志性
将上面的代码中申请内存空间函数稍作如下修改,其余函数调用都不变
char *GetMemory(ULONGS size)
{
char * pMem = new(nothrow) char[size];//分配失败,指针为空
if(NULL == pMem)
{
cout<<"Alloc Memory failure!"<<endl;
}
return pMem;
}
运行该段程序,则运行结果显示申请空间失败后指针为空,运行结果如下所示: