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

后端 未结 8 781
别那么骄傲
别那么骄傲 2020-12-29 19:17

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

8条回答
  •  粉色の甜心
    2020-12-29 19:25

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

提交回复
热议问题