经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
new会返回NULL空指针吗
来源:cnblogs  作者:willhua  时间:2018/12/14 9:34:40  对本文有异议

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号