new会返回NULL空指针吗

c++中的new会返回NULL空指针吗

https://stackoverflow.com/questions/3389420/will-new-operator-return-nullc++

On a standards-conforming C++ implementation, no. 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).
On some older C++ compilers (especially those that were released before the language was standardized) or in situations where exceptions are explicitly disabled (for example, perhaps some compilers for embedded systems), new may return NULL on failure. Compilers that do this do not conform to the C++ standard.less

在符合C++标准的实现版本中,答案是不会。在正常状况下,若是new失败,那么就会thrown一个std::bad_alloc。在以下状况下会返回NULL来指明失败:this

  1. 使用nothrow,T *p = new (std::nothrow) T(args);
  2. 一些旧的编译器中,尤为是在C++标准发布以前的编译器
  3. 明确禁用exceptions,好比一些嵌入式系统的编译器

为何呢?

https://stackoverflow.com/questions/26419786/why-doesnt-new-in-c-return-null-on-failure/26420011url

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

有一个原则叫作DRY,即don't repeat yourself,这个yourself指的是把可能会致使错误的机会一直endless的传递下去。若是在new返回空指针,那么在使用new的返回值的下一个场景中也须要检查是不是空指针,这样的check会一直传递下去。而抛出异常就会终止这个传递。.net

相关文章
相关标签/搜索