new会返回NULL空指针吗
c++中的new会返回NULL空指针吗
On a standards-conforming C++ implementation, no. The ordinary form of new will never return NULL; if allocation fails, a
nullpointerexception为什么异常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,⽐如⼀些嵌⼊式系统的编译器
为什么呢?
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会⼀直传递下去。⽽抛出异常就会终⽌这个传递。