关于set_new_handler()
#include <iostream>
#include <new.h>
#include <new.h>
using namespace std;
int nomorememory(size_t size)
{
cout << "Allocation failed. Coalescing heap." << endl;
{
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;
}
{
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函数。