tags:

views:

92

answers:

5

it it possible that in some cases NEW returns some value, for example NULL, or it will always throw exception? thanks in advance

+1  A: 

http://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.

Merlyn Morgan-Graham
Installing a custom "new handler" can never make `new` to return 0. If that handler returns, the memory allocation will be re-attempted. The semantics in that case are well-defined and certainly not "all bets are off". Disabling exceptions is another matter though, then you have to consult the compiler's documentation...
usta
@usta: Writing posts late at night :) Thanks for the correction, and will fix
Merlyn Morgan-Graham
+2  A: 

char *p = new(std::nothrow) char[1024];

Alexey Malistov
Jut one point the answer assumes std namespace is included, Otherwise need to explicitly specify std::nothrow
Als
yes, you're right.
Alexey Malistov
+1  A: 

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();
GMan
A: 

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).

ereOn
+1  A: 

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;

Naveen