Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't new in C++ return NULL on failure

Tags:

c++

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?

like image 788
NDestiny Avatar asked Oct 17 '14 07:10

NDestiny


People also ask

What does new operator returns on failure?

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.

Does new operator return null?

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

What happens if new fails to allocate memory?

If the new operator fails to allocate memory it returns NULL which can be used to detect failure or success of new operator.

Can you return NULL in C?

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.


1 Answers

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

like image 72
Cheers and hth. - Alf Avatar answered Oct 07 '22 18:10

Cheers and hth. - Alf