new會返回NULL空指針嗎


c++中的new會返回NULL空指針嗎

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

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.

在符合C++標准的實現版本中,答案是不會。在正常情況下,如果new失敗,那么就會thrown一個std::bad_alloc。在如下情況下會返回NULL來指明失敗:

  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/26420011

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

有一個原則叫做DRY,即don't repeat yourself,這個yourself指的是把可能會導致錯誤的機會一直endless的傳遞下去。如果在new返回空指針,那么在使用new的返回值的下一個場景中也需要檢查是否是空指針,這樣的check會一直傳遞下去。而拋出異常就會終止這個傳遞。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM