关于operator new 的问题
KingI 2005-08-26 03:44:47 #include <iostream>
using namespace std;
#include <new>
#include <exception>
class A
{
double i;
public:
A(int n=0) : i(n) { }
static void * operator new [](size_t size) throw (bad_alloc &);
static void operator delete [](void *p);
};
void * A::operator new [](size_t size) throw (bad_alloc &)
{
void *mem;
/* try { //问题就在这里
mem=::operator new (size);
}catch(...) {
throw bad_alloc();
}
*/
mem=::operator new (size);
if (!mem)
throw bad_alloc();
return mem;
}
void A::operator delete [](void *p)
{
::operator delete (p);
}
void main()
{
A *a=NULL;
try {
a=new A[500000000];
}catch(bad_alloc &err) {
cerr<<err.what()<<endl;
return ;
}
delete []a;
cout<<"Done!\n";
}
问题就在这个void * A::operator new [](size_t size) throw (bad_alloc &)函数中:
为什么用异常处理机制捕捉不到内存不足的异常,而用if(!mem)可以成功呢?
全局的operator new中应该会抛出异常吧?