Why doesn't new
return NULL
on failure? Why does it throw an exception only on failure?
As it returns a pointer to the object on successes, why not on failure? Is there any specific reason for this behaviour?
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.
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).
If the new operator fails to allocate memory it returns NULL which can be used to detect failure or success of new operator.
NULL can be used if a function returns a pointer. In this case, you return an object, which means that you have to return a real, existing object. One way of doing this is to have an "ok" field in the struct that you could set in the init function, and that you could check in the caller.
Before exceptions were introduced in C++:
A failing new
-expression produced a nullpointer.
In a failing constructor one assigned a nullpointer to this
.
After exceptions were introduced:
A failing ordinary new
-expression throws an exception.
In a failing constructor one throws an exception.
One difference is that failure reporting for constructors now works also for creation of objects without dynamic allocation.
Another difference is that code using new
-expressions now can be simpler since the error handling can be moved out of each such code place, and centralized.
The old nullpointer-result behavior is still available via std::nothrow
(include the <new>
header). This implies checking at each place using new
. Thus nullpointer results are in conflict with the DRY principle, don't repeat yourself (the redundancy offers an endless stream of opportunities to introduce errors).
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