Chinaunix首页 | 论坛 | 博客
  • 博客访问: 329381
  • 博文数量: 79
  • 博客积分: 2466
  • 博客等级: 大尉
  • 技术积分: 880
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-07 16:47
文章分类

全部博文(79)

文章存档

2014年(3)

2012年(7)

2011年(14)

2010年(2)

2009年(2)

2008年(2)

2007年(18)

2006年(31)

分类: C/C++

2011-07-14 06:59:32

《Exceptional C++》上说,如果new一个对象数组的时候,其中的某一个对象的构造过程抛出异常,之前成功构造的所有对象的析构函数会被调用,分配到的内存也会被释放,因此这个new操作本身,在任何异常面前不会泄漏资源。这个根据在C++标准(ISO/IEC 14882:2003(E))的15.2.2小节: 

An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution.  Should a constructor for an element of an automatic array throw an exception, only the constructed elements of that array will be destroyed.  If the object or array was allocated in a new-expression, the matching deallocation function (3.7.3.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.

下面是程序和运行结果,可以看到第三个T的构造函数抛出异常时,前两个T实例都被正确析构了。

#include

class T {
private:
  static int count;
public:
  T() {
    printf("T constructor\n");
    if (++count > 2)
       throw int(47);
  }

  ~T() { printf("T destructor\n"); }
};

int T::count = 0;

int
main(int argc, char** argv) {
  try {
    T *arr = new T[20];
  }
  catch (...) {
    printf("Caught exception!\n");
  }
  return 0;
}


运行结果是:
$ ./a.out
T constructor
T constructor
T constructor
T destructor
T destructor
Caught exception!
$

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