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

相關文章
相關標籤/搜索