return value of NEW
it it possible that in some cases NEW
returns some value, for example NULL, or it will 开发者_如何学编程always throw exception?
char *p = new(std::nothrow) char[1024];
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();
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.
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;
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)
.
精彩评论