为什么C ++中的新功能失败后不会返回NULL [英] Why doesn't new in C++ return NULL on failure

查看:71
本文介绍了为什么C ++中的新功能失败后不会返回NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 new 在失败时不返回 NULL ?为什么只在失败时抛出异常?

Why doesn't new return NULL on failure? Why does it throw an exception only on failure?

当成功时它返回指向对象的指针,为什么不失败?

As it returns a pointer to the object on successes, why not on failure? Is there any specific reason for this behaviour?

推荐答案

在C ++中引入异常之前:

Before exceptions were introduced in C++:


  • 失败的 new 表达式产生了一个空指针。

  • A failing new-expression produced a nullpointer.

在一个失败的构造函数中,为 this 分配了一个空指针。

In a failing constructor one assigned a nullpointer to this.

在引入例外之后:


  • 失败的普通 new -expression引发异常。

  • A failing ordinary new-expression throws an exception.

在失败的构造函数中,引发异常。

In a failing constructor one throws an exception.

一个区别是,构造函数的故障报告现在也可以用于创建没有动态分配的对象。

One difference is that failure reporting for constructors now works also for creation of objects without dynamic allocation.

另一个区别是因为现在可以使用 new 表达式来简化代码了,因为可以将错误处理移出每个这样的代码位置并进行集中处理。

Another difference is that code using new-expressions now can be simpler since the error handling can be moved out of each such code place, and centralized.

旧的nullpointer-result行为仍然可以通过 std :: no获得抛出(包括< new> 标头)。这意味着使用 new 在每个位置进行检查。因此,空指针结果与DRY原理冲突,不要重复自己(冗余提供了无尽的机会引入错误)。

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

这篇关于为什么C ++中的新功能失败后不会返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆