当前位置: 移动技术网 > IT编程>开发语言>C/C++ > new会返回NULL空指针吗

new会返回NULL空指针吗

2018年12月13日  | 移动技术网IT编程  | 我要评论

霉干菜烧饼,侍从官之肩在哪,红海行动手机 在线观看

c++中的new会返回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,比如一些嵌入式系统的编译器

为什么呢?

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会一直传递下去。而抛出异常就会终止这个传递。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网