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

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

    In C, all requests for dynamic memory are made by function calls; it's necessary that code check any allocation requests to see if they return null, but there is a well-defined place where such checks can be made (i.e. right after the call). In C++, while it is possible for code to construct objects by calling new, most objects are created by creating an object in which they play a part.

    Given:

    class Story
    {
      Potter harry;
      Weasley ron,ginny,george,fred;
      Grainger hermione;
      Longbottom neville;
      Creevy colin;
      Story()
      {
      }
    }
    

    If the constructor for harry tries to create a new object and fails, the only way to prevent the system from trying uselessly to create objects for all the other fields would be to have the constructor throw an exception. Even though the constructor for harry failed, the other constructors might succeed in creating those objects if they require less memory than a Potter object; since the failure to create harry would render the Story object useless, however, any effort spent creating objects for the remaining fields would not only be wasted, but would require the system to expend even more effort destroying those uselessly-created objects.

    Since in most cases the only thing the system would be able to do when new fails is to throw an exception, it's easier to have new throw the exception itself and have code catch the exception if necessary, than to require that all code which calls new must check whether it succeeded and throw an exception if it didn't.

提交回复
热议问题