, new, bad_alloc. . bad_alloc. .
#include <new>
#include <iostream>
using namespace std;
int main()
{ double *p;
try{
while(1) p=new double[100]; //
}
catch(bad_alloc exept) { // xalloc
cout<<" "<<exept.what()<<endl;
}
return 0;
}
bad_alloc, :
#include <new>
#include <iostream>
using namespace std;
int main()
{ double *p;
try{
if(!(p=new double[100000000])) // p==NULL
throw bad_alloc; //
}
catch(bad_alloc exept) { // bad_alloc
cout<<" "<<exept.what()<<endl;
}
return 0;
}
:
bad allocation
new C++ , , NULL. , new , set_new_handler() 0. , set_new_handler() , . set_new_handler ( new) , void.
#include<new>
#include<iostream>
using namespace std;
void newhandler()
{ cout << "The new_handler is called: ";
throw bad_alloc();
return;
}
int main()
{ char* ptr;
set_new_handler (newhandler);
try {
ptr = new char[~size_t(0)/2];
delete[ ] ptr;
}
catch(bad_alloc &ba) {
cout << ba.what() << endl;
}
return 0;
}
The new_handler is called: bad allocation
new _set_new_handler, , int size_t, :
#include <new>
#include <iostream>
using namespace std;
int error_alloc(size_t) // size_t unsigned integer sizeof operator.
{ cout << " " <<endl;
return 0;
}
int main()
{
_set_new_handler(error_alloc);
int *p = new int[10000000000];
return 0;
}
:
, - set_new_handler, new bad_alloc.