Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Mar 9, 1998

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
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date