I usually never see test for new in C++ and I was wondering why.
Foo *f = new Foo;
// f is assumed as allocated, why usually, nobody test the return of new?
new int is a new expression. The language defines that it returns an int* . Among other things it also calls the new operator, which, yes, returns a void* , because it just allocates raw storage. The constructor (empty for int ) turns raw storage into an initialized object.
The ordinary form of new will never return NULL ; if allocation fails, a std::bad_alloc exception will be thrown (the new (nothrow) form does not throw exceptions, and will return NULL if allocation fails).
In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).
When the nothrow constant is passed as second parameter to operator new , operator new returns a null-pointer on failure instead of throwing a bad_alloc exception. nothrow_t is the type of constant nothrow . A pointer to an already-allocated memory block of the proper size.
As per the current standard, new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "(std::nothrow)". i.e.
Foo* foo = new (std::nothrow) Foo;
Of course, if you have a very old or possibly broken toolchain it might not follow the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With