关于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中应该会抛出异常吧?
...全文
130 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
horris 2005-08-28
  • 打赏
  • 举报
回复
mark and help up
bugebear3 2005-08-26
  • 打赏
  • 举报
回复
一直对异常都不太清楚,向楼上的学习
KingI 2005-08-26
  • 打赏
  • 举报
回复
To:fireman_lh()
刚才试了一下,可是编译器报错:error C2039: 'set_new_handler' : is not a member of 'std'
fireman_lh 2005-08-26
  • 打赏
  • 举报
回复
我一直有个问题想问的是,如果在这里不把globalhandler重载回去的话,系统的globalhandler会一直保持这个吗?
fireman_lh 2005-08-26
  • 打赏
  • 举报
回复
template<class t>
void * newhandlersupport<t>::operator new(size_t size)
{
new_handler globalhandler =
std::set_new_handler(currenthandler);
void *memory;
try {
memory = ::operator new(size);
}
catch (std::bad_alloc&) {
std::set_new_handler(globalhandler);
throw;
}

std::set_new_handler(globalhandler);
return memory;
}
fireman_lh 2005-08-26
  • 打赏
  • 举报
回复
在effective c++中这里是把set_new_handler出去的globalhandler再重新加载回来的

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧