What happens when new fails in C++

When malloc() fails, it will return a null pointer. But… What about new? It throws an exception… correct! But… What about the pointer? Any pointers returned?

See following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Author Name: Need-Being
// Modification date: 22/03/2012
// File description: Sample code to show what happens when throw exception in
//                   constructor.
 
#include <iostream>
using namespace std;
 
class Object
{
public:
	Object()
	{
		cout << "Object: Constructor called" << endl;
	}
 
	~Object()
	{
		cout << "Object: Destructor called" << endl;
	}
 
};
 
class Test
{
public:
	Test()
	{
		cout << "Test: Constructor called" << endl;
		throw 0; // Throw a exception by force
	}
 
	~Test()
	{
		cout << "Test: Destructor called" << endl;
	}
private:
	Object object;
};
 
int main()
{
	Test* test = (Test*)1;
 
	printf("Test pointer: %p\n", test);
 
	try {
		test = new Test();
	} catch (...) {
		cout << "Exception caught" << endl;
	}
 
	printf("Test pointer: %p\n", test);
 
	return 0;
}

Running result:
Test pointer: 0x1
Object: Constructor called
Test: Constructor called
Object: Destructor called
Exception caught
Test pointer: 0x1

In this case you can find out that the Test instance is freed without calling its destructor. Also, the value of test is not changed.

Published by

Need-Being

You never know me... Need-Being... Human Being? or Just Being Here...

Leave a Reply

Your email address will not be published. Required fields are marked *