What about not using nothrow
argument on new
operator? Does it also returns null
?
The C++ standard (§18.4.1.1) defines operator new as:
void* operator new (std::size_t size) throw (std::bad_alloc);
So the standard behavior of new which takes one argument is to throw a std::bad_alloc
in case of failure.
The standard also defines a nothrow
new version which takes two parameters:
void* operator new(std::size_t size, const std::nothrow_t&) throw();
This version returns a NULL
in case of failure, but note that to use this version you explicitly need to pass an additional parameter to the new operator.
When should you use nothrow
version?
Ideally, You should always use the standard version of new which throws a bad_alloc
. You should stick to that recommendation always. However, in some situations you might be forced to use the nothrow
version. Some of such situations are:
- You are working with older C++ compilers (released before the language was standardized) which do not support exceptions.
- The target platforms where exceptions are explicitly disabled (ex: embedded systems) or not guaranteed to work correctly.
- Post 1990's the standard behavior of
new
was to return NULL
, if you are working with a lot of legacy code which relies on this behavior.