Article ID: 167733
Article Last Modified on 1/9/2006
#include <new>
#include <new.h>
int my_new_handler(size_t) {
throw std::bad_alloc();
return 0;
}
int main () {
_PNH _old_new_handler;
_old_new_handler = _set_new_handler(my_new_handler);
/* ... application processing ... */
_set_new_handler(_old_new_handler);
return 0;
} To call new handler when malloc fails to obtain the requested block of
memory, use the _set_new_mode function.
#include <new>
#include <new.h>
#pragma init_seg(lib)
int my_new_handler(size_t) {
throw std::bad_alloc();
return 0;
}
struct my_new_handler_obj{
_PNH _old_new_handler;
int _old_new_mode;
_tag_g_new_handler_obj() {
_old_new_mode = _set_new_mode(1);
_old_new_handler = _set_new_handler(my_new_handler);
}
~_tag_g_new_handler_obj() {
_set_new_handler(_old_new_handler);
_set_new_mode(_old_new_mode);
}
} _g_new_handler_obj; Operator new, as implemented by Visual C++ 5.0, ignores the function
exception specification. So new(std::nothrow) still generates an exception if
your new handler is installed to throw an exception as the examples above
demonstrate. To change this behavior, override operator new as follows:
void *__cdecl operator new(size_t cb, const std::nothrow_t&) throw()
{
char *p;
try {
p = new char[cb];
}
catch (std::bad_alloc) {
p = 0;
}
return p;
}
Using _set_new_handler
http://msdn.microsoft.com/library/en-us/vccelng/htm/specl_28.asp
_set_new_handler
http://msdn.microsoft.com/library/en-us/vclib/html/_CRT__set_new_handler.asp
_set_new_mode
http://msdn.microsoft.com/library/en-us/vclib/html/_CRT__set_new_mode.asp
init_seg
http://msdn.microsoft.com/library/en-us/dv_vccelng4/html/ellrfinitusseg.asp
Keywords: kbhowto kbtshoot kbprb kbcpponly kbcompiler KB167733