没有内存泄漏。只有在BadClass
它本身动态地分配内容,并且从未在析构函数中释放它。因为我们忽略了你BadClass
实现,而不是猜测,这取决于您。必由之路new BadClass[N];
泄漏内存本身就是如果它完成了,然后抛出对它的唯一引用,您将手动管理(array
).
动态分配的数组,在其中一个构造函数中为其中的元素抛出,将(A)对已经构造的元素以相反的顺序退出析构函数,(B)释放分配的内存,最后(C)将实际抛出到最近的CATCH处理程序(或在没有任何情况下的默认处理程序)。
由于抛出发生,因此对结果数组指针的分配永远不会发生,因此不需要。delete[]
.
最好的例子是:
#include <iostream>
struct A
{
static int count;
int n;
A() : n(++count)
{
std::cout << "constructing " << n << '\n';
if (count >= 5)
throw std::runtime_error("oops");
}
~A()
{
std::cout << "destroying " << n << '\n';
}
};
int A::count;
int main()
{
A *ar = nullptr;
try
{
ar = new A[10];
}
catch(std::exception const& ex)
{
std::cerr << ex.what() << '\n';
}
}
输出量
constructing 1
constructing 2
constructing 3
constructing 4
constructing 5
destroying 4
destroying 3
destroying 2
destroying 1
oops
注意,因为元素‘5’的构造从未完成,因此它的析构函数不会被触发。不过,委员认为都是成功建造是破坏(在上面的例子中没有演示,但是如果你愿意的话,这是一个有趣的练习)。
所有这一切,不管如何,都要使用智能指针。