FAQ 12.06 Should the pointer returned from new Fred() be checked to see if it is NULL ?

FAQ 12.06 Should the pointer returned from new Fred() be checked to see if it is NULL?

graphics/new_icon.gif

No, new Fred() never ever returns NULL. Instead, if new runs out of memory during new Fred(), it throws an exception of type bad_alloc (see FAQ 9.02).

Because of this, the if test in the following example is considered bad form since it increases code size, increases code complexity, and increases testing costs, yet it adds no value (remember, exceptions guarantee that p will never be NULL).

 #include <new> using namespace std; class Fred { }; void sample() throw(bad_alloc) {   Fred* p = new Fred();   if (p == NULL) {                                   <-- 1     // ...   }   // ... } int main() { sample(); } 

(1) Bad Form! Shouldn't check for NULL

C programmers please note that this behavior is very different from the way out-of-memory is handled by malloc(). To be safe, every call to malloc() has to be followed by an explicict if test to see if malloc() returned NULL.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net