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

本文探讨了在VC++环境下使用_set_new_handler处理内存分配失败的方法。通过定义特定的处理函数,可以有效地管理内存分配失败的情况。文章详细解释了如何设置处理函数及其返回值的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
关于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函数。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值