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

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

    It is by design. In C++ every kind of failure is notified by throwing an exception by default — streams, however, are exception, which does not throw exception (pun intended) by default.

    You can use nothrow version as:

    T *p = new (std::nothrow) T(args);
    
    if ( p == nullptr ) //must check for nullity
    {
         std::cout << "memory allocation failed" << std::endl;
    }
    

提交回复
热议问题