Item 49: Understand the behavior of the new-handler(Effective C++)
set_new_handler allows you to specify a function to be called when memory allocation requests cannot be satisfied.
Nothrow new is of limited utility, because it applies only to memory allocation; subsequent constructor calls may still throw exceptions.
Nothrow new is of limited utility, because it applies only to memory allocation; subsequent constructor calls may still throw exceptions.
1 #include <iostream>
2 using namespace std;
3
4 class Foo
5 {
6 public:
7 Foo(){}
8 static new_handler set_new_handler(new_handler p) throw();
9 void* operator new(size_t size);
10 private:
11 static new_handler currentHandler;
12 };
13
14 new_handler Foo::currentHandler = 0;
15
16 void* Foo::operator new(size_t size)
17 {
18 throw bad_alloc();
19 }
20
21 new_handler Foo::set_new_handler(new_handler p) throw()
22 {
23 //new_handler oldHandler = currentHandler;
24 //currentHandler = p;
25 std::set_new_handler(p);
26 return p;
27 //return oldHandler;
28 }
29
30 void outOfMem()
31 {
32 cout << "out of memory" << endl;
33 }
34
35 int main()
36 {
37 set_new_handler(outOfMem);
38 cout << "Attempting to allocate 1 GB...";
39 char* p = new char [1024*1024*1024*1024*1024];
40 cout << "Ok\n";
41 delete[] p;
42 cin.get();
43 return 0;
44 }
2 using namespace std;
3
4 class Foo
5 {
6 public:
7 Foo(){}
8 static new_handler set_new_handler(new_handler p) throw();
9 void* operator new(size_t size);
10 private:
11 static new_handler currentHandler;
12 };
13
14 new_handler Foo::currentHandler = 0;
15
16 void* Foo::operator new(size_t size)
17 {
18 throw bad_alloc();
19 }
20
21 new_handler Foo::set_new_handler(new_handler p) throw()
22 {
23 //new_handler oldHandler = currentHandler;
24 //currentHandler = p;
25 std::set_new_handler(p);
26 return p;
27 //return oldHandler;
28 }
29
30 void outOfMem()
31 {
32 cout << "out of memory" << endl;
33 }
34
35 int main()
36 {
37 set_new_handler(outOfMem);
38 cout << "Attempting to allocate 1 GB...";
39 char* p = new char [1024*1024*1024*1024*1024];
40 cout << "Ok\n";
41 delete[] p;
42 cin.get();
43 return 0;
44 }