http://bbs.byr.cn/article/CPP/49138
网上看的一段code,讲new的用法的,注释中那个红字就是我的问题,可能有点钻牛角尖,但是确实想知道为什么
#include <iostream>
#include <new>
using namespace std;
char *GetMemory(unsigned long size)
{
char *p=new(nothrow) char[size];//分配失败,是返回NULL
if(NULL==p)
cout<<"alloc failure!"<<endl;
return p;
}
int main()
{
try
{
char *p=GetMemory(10e11);
if(p==NULL)
cout<<"failure"<<endl;
delete [] p;//如果是NULL,为什么还要delete?
}
catch(const std::bad_alloc &ex)
{
cout<<ex.what()<<endl;
}
return 0;
}
在VS2008,跟踪operator delete的源码发现
void operator delete(
void *pUserData
)
{
_CrtMemBlockHeader * pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
.......
这里已经对空指针做了预防。。。。