C++学习之new返回值的误用-new(nothrow)

来源:互联网 发布:json数据生成工具 编辑:程序博客网 时间:2024/04/30 21:21

转自:http://blog.csdn.net/starryheavens/article/details/7002404

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判断分配是否成功是徒劳的。


2.nothrow new/delete不抛出异常的运算符new的形式,new失败时返回NULL。

定义如下:

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的标志性哑元

测试程序:

#include "stdafx.h"
#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;

}
catch(const std::bad_alloc &ex)
{
cout<<ex.what()<<endl;
}

return 0;
}

0 0
原创粉丝点击