Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92450628
  • 博文数量: 19283
  • 博客积分: 9968
  • 博客等级: 上将
  • 技术积分: 196062
  • 用 户 组: 普通用户
  • 注册时间: 2007-02-07 14:28
文章分类

全部博文(19283)

文章存档

2011年(1)

2009年(125)

2008年(19094)

2007年(63)

分类: C/C++

2008-04-16 18:50:51

    来源:Blog    作者:fatalerror99

直到 1993 年,C++ 还要求 operator new 不能分配被请求的内存时要返回 null。operator new 现在则被指定抛出一个 bad_alloc exception,但是很多 C++ 程序是在编译器开始支持这个修订标准之前写成的。C++ 标准化委员会不想遗弃这些 test-for-null(检验是否为 null)的代码基础,所以他们提供了 operator new 的另一种可选形式,用以提供传统的 failure-yields-null(失败导致 null)的行为。这些形式被称为 "nothrow" 形式,这在一定程度上是因为它们在使用 new 的地方使用了 nothrow objects(定义在头文件 中):

class Widget { ... };
Widget *pw1 = new Widget; // throws bad_alloc if
// allocation fails

if (pw1 == 0) ... // this test must fail

Widget *pw2 =new (std::nothrow) Widget; // returns 0 if allocation for
// the Widget fails

if (pw2 == 0) ... // this test may succeed

  对于异常,nothrow new 提供了比最初看上去更少的强制保证。在表达式 "new (std::nothrow) Widget" 中,发生了两件事。首先,operator new 的 nothrow 版本被调用来为一个 Widget object 分配足够的内存。如果这个分配失败,众所周知,operator new 返回 null pointer。然而,如果它成功了,Widget constructor 被调用,而在此刻,所有打的赌都失效了。Widget constructor 能做任何它想做的事。它可能自己 new 出来一些内存,而如果它这样做了,它并没有被强迫使用 nothrow new。那么,虽然在 "new (std::nothrow) Widget" 中调用的 operator new 不会抛出,Widget constructor 却可以。如果它这样做了,exception 像往常一样被传播。结论?使用 nothrow new 只能保证 operator new 不会抛出,不能保证一个像 "new (std::nothrow) Widget" 这样的表达式绝不会导致一个 exception。在所有的可能性中,你最好绝不需要 nothrow new。

  无论你是使用 "normal"(也就是说,exception-throwing)new,还是它的稍微有些矮小的堂兄弟,理解 new-handler 的行为是很重要的,因为它可以用于两种形式。

  Things to Remember

  ·set_new_handler 允许你指定一个当内存分配请求不能被满足时可以被调用的函数。

  ·nothrow new 作用有限,因为它仅适用于内存分配,随后的 constructor 调用可能依然会抛出 exceptions。

阅读(219) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~