您的位置:首页 > 编程语言 > C语言/C++

学习中遇到的问题-关于set_new_handler()

2007-08-25 14:09 549 查看
 
关于set_new_handler()

#include <iostream>
#include <new.h>
using namespace std;
int nomorememory(size_t size)
{
   cout << "Allocation failed. Coalescing heap." << endl;
    return 0;//try return 0;
}
void nomorememory1()
{
   cout << "Allocation failed. Coalescing heap." << endl;
}
int main(int argc, char* argv[])
{
 _set_new_handler(nomorememory);
 try{
  int *pbigdataarray = new int[1000000000];
  if(pbigdataarray==NULL)
    cout<<"wrong"<<endl;  
 }
 catch(bad_alloc a)
 {
  cout<<"test1"<<endl;
 }
 catch(...)
 {
  cout<<"test2"<<endl;
 }
 cout<<"finish"<<endl;
 return 0;
}
/***************/
 
问题:
首先在vc6.0(xp)下,使用set_new_handler(nomorememory1);运行时出现assert错误。查看set_new_handler源码发现有assert(new_p==0).说明该函数只能这样用set_new_handler(0)。这是在VC++中得到的结果,这说明在使用的编译器中没有实现标准规定的   set_new_handler()函数。
故采用_set_new_handler(nomorememory)替换set_new_handler。其中nomorememory函数的参数size为申请的内存的大小。nomorememory函数的返回值如果0则表明分配失败,如果非0则表明应该抽取分配的内存。当new发现nomorememory返回0,则new返回0. 当new发现nomorememory返回非0,则new抽取分配的内存。
在实际使用中发现,如果nomorememory返回非0,当new无法满足内存需求时,它会不只一次的调用nomorememory函数, 它会不断的调用,直道找到足够的内存。如果nomorememory返回0,则new返回0,并且只调用一次nomorememory函数。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息