1 #include <iostream>
2 namespace std {
3 typedef void (*new_handler)();
4
5 class NewHandlerHolder {
6 public:
7 explicit NewHandlerHolder(std::new_handler nh)
8 : handler(nh){}
9 ~NewHandlerHolder(){
10 std::set_new_handler(handler);
11 }
12 private:
13 std::new_handler handler;
14 NewHandlerHolder(const NewHandlerHolder& );
15 NewHandlerHolder& operator=(const NewHandlerHolder&);
16 };
17
18 template <typename T>
19 class NewHandlerSupport {
20 public:
21 static std::new_handler set_new_handler(std::new_handler p) throw();
22 static void* operator new(std::size_t size) throw(std::bad_alloc);
23 private:
24 static std::new_handler currentHandler;
25 };
26
27 template <typename T>
28 std::new_handler
29 NewHandlerSupport<T>::set_new_handler(std::new_handler p) throw()
30 {
31 std::new_handler oldHandler = currentHandler;
32 currentHandler = p;
33 return oldHandler;
34 }
35
36 template <typename T>
37 void* NewHandlerSupport<T>::operator new(std::size_t size) throw(std::bad_alloc)
38 {
39 NewHandlerHolder h(std::set_new_handler(currentHandler));
40 return ::operator new(size);
41 }
42
43 template <typename T>
44 std::new_handler NewHandlerSupport<T>::currentHandler = 0;
45 };
46
该代码已经通过gcc 4.4.1编译