it it possible that in some cases NEW returns some value, for example NULL, or it will always throw exception? thanks in advance
views:
92answers:
5http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.6
Take heart. In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never returns NULL!
[Unless your compiler "is ancient", in which case that page has a solution for you, too].
Note that if you disable exceptions in your compiler options, then you should check your compiler docs about what you can expect.
A standards compliant new expression never evaluates to null.
You may use std::nothrow to return null instead of throw an exception:
new (std::nothrow) T();
new throws (std::bad_alloc if I remember well) when the allocation fails.
But you can change this behavior to mimic malloc() and return NULL instead, using (std::nothrow).
According to standard whenever new fails it should throw std::bad_alloc exception. However, you can make new to return NULL in case of failure using std::nothrow. For example: int *p = new(std::nothrow) int;