1.C++标准对内存分配失败有明确的规定,调用new_handel()函数会有:
1.用new分配给多的内存,
2.抛出bad_alloc异常
3.调用exit退出
上代码:
#include<stdio.h>
#include<new>
#include<algorithm>
#include<iostream>
using namespace std;
char *gPool=NULL;
void my_new_handler();
int main()
{
set_new_handler(my_new_handler);
gPool=new char[100*1024*1024];
return 0;
}
void my_new_handler()
{
if(gPool!=NULL)
{
cout<<"try to get more memory.....\n";
delete[] gPool;
gPool=NULL;
return ;
}
else
{
cout<<"i can not help....\n";
// throw bad_alloc();
}
return ;
}
对于operator new中进行改变称为placement new,我们可以写自定义的全局operator new函数,和成员函数。