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.

Disable warnings of third-party headers

Sometimes it is very annoying that the compiler always tells me there is a lot of warning in third-party headers. For example, boost headers.

After google awhile and found a solution to that in Stack-flow.
Just use #pragma to wrap the third-party and it’s done!

For example:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#include <boost/thread.hpp>
#pragma GCC diagnostic pop

Not a good idea to throw exceptions in destructor in C++

When using try-catch blocks in C++, it is not a good to throw exceptions in destructor. Briefly, it may cause SIGABORT at runtime since the exception thrown in destructor may not be caught.

In MAC OS, you will get a “terminate called without an active exception” error. Then cause unexpected errors further on.

In Linux and Windows, the exception thrown in destructor will be caught by system. Then the program terminates

Continue reading Not a good idea to throw exceptions in destructor in C++