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

后端 未结 8 777
别那么骄傲
别那么骄傲 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:28

    By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as argument for new, it returns a null pointer instead.

    The nothrow constant is a value of type nothrow_t, with the only purpose of triggering an overloaded version of the function operator new (or operator new[]) that takes an argument of this type. The value itself is not used, but that version of operator new shall return a null pointer in case of failure instead of throwing an exception.

提交回复
热议问题