Exceptions and operator new

Standard C++ states that operator new should throw an exception of type std::bad_alloc when it fails. This is different from previous stages of C++ and it means two important things: 1. If your code does not contain a catch statement to handle an std::bad_alloc exception, your program will crash whenever new fails, even if that exception occurs deep down in some library routine you never knew was there.2. Testing whether the pointer returned from new == 0 is completely useless; in case of success, your test will waste system resources in vain, checking a condition which is already guaranteed to be false. (Because no exception has been thrown, the tested pointer cannot be a null pointer.). And in cases of failure, the thrown exception will abort the current thread of execution right from where it was thrown, so the next lines of code will not be executed:

 void* f(int size) {	char *p = new char [size]; 	//A COMPLETELY USELESS TEST	If (p == 0) { //we won

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: