《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!
$
阅读(520) | 评论(0) | 转发(0) |