int*p1=new int;//1
int*p2=new(nothrow)int;//2
int a;
int*p3=new(&a)int;//3
1.常用的方法,其对应的原函数为:
void*__CRTDECL operator new(size_t size)_THROW1(_STD bad_alloc)
{//try to allocate size bytes
void*p;
while((p=malloc(size))==0)
if(_callnewh(size)==0)
{//report no memory
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return(p);
}
其中:
#define_THROW1(x)throw(...)
#define_RAISE(x)throw x
throw(...)在函数声明中,表示函数中有抛出异常处理。
2.不抛出异常的方法,其对应的原函数为:
void*__CRTDECL operator new(size_t count,const std::nothrow_t&)
_THROW0()
{//try to allocate count bytes
void*p;
_TRY_BEGIN
p=operator new(count);
_CATCH_ALL
p=0;
_CATCH_END
return(p);
}
其中:
#define_THROW0()throw()
#define_TRY_BEGIN try{
#define_CATCH(x)}catch(x){
#define_CATCH_ALL}catch(...){
#define_CATCH_END}
这个函数调用了p=operator new(count)这是1中所说的形式,也就是可能有异常,但是2方法的原函数对这个异常有了处理,所以从整个函数来看是没有抛出异常的,实际上是函数本身调用了常规的new函数,然后并对异常做了处理。
throw()在函数声明中,表示函数中不抛出异常处理。
3.不申请新内存的方法,其原函数为:
inline void*__CRTDECL operator new(size_t,void*_Where)_THROW0() {//construct array with placement at_Where
return(_Where);
}
直接把已有的内存地址返还给某个指针变量。_THROW0()表示函数中不抛出异常。下载本文