#include <iostream>
#include <new>
#include <stdlib.h>
class NewHandlerHolder
{
public:
trueexplicit NewHandlerHolder(std::new_handler nh) : handler(nh) { };
true~NewHandlerHolder() { std::set_new_handler(handler); }
private:
truestd::new_handler handler;
trueNewHandlerHolder(const NewHandlerHolder&);
trueNewHandlerHolder& operator=(const NewHandlerHolder&);
};
template<typename T>
class NewHandlerSupport
{
public:
truestatic std::new_handler set_new_handler(std::new_handler p) throw();
truestatic void* operator new(std::size_t size) throw(std::bad_alloc);
private:
truestatic std::new_handler currentHandler;
};
template<typename T>
std:: new_handler NewHandlerSupport<T>::set_new_handler(std::new_handler p) throw()
{
truestd::new_handler oldHandler = currentHandler;
truecurrentHandler = p;
truereturn oldHandler;
}
template<typename T>
void* NewHandlerSupport<T>::operator new(std::size_t size) throw(std::bad_alloc)
{
trueNewHandlerHolder h(std::set_new_handler(currentHandler));
truereturn ::operator new(size);
}
template<typename T>
std::new_handler NewHandlerSupport<T>::currentHandler = 0;
class Widget : public NewHandlerSupport<Widget>
{
true
};
void outOfMem()
{
truestd::cerr << "Unable to satisfy request for memory\n";
trueabort();
}
int main()
{
true
trueWidget::set_new_handler(outOfMem);
true
trueWidget* pw1 = new Widget;
true
truestd::string* ps = new std::string;
true
trueWidget::set_new_handler(0);
true
trueWidget* pw2 = new Widget;
truereturn 0;
}