在C++中常见问题,在[16.16]给出了下面的例子,删除多维数组
void manipulateArray(unsigned nrows, unsigned ncols[])
{
typedef Fred* FredPtr;
FredPtr* matrix = new FredPtr[nrows];
// Set each element to NULL in case there is an exception later.
// (See comments at the top of the try block for rationale.)
for (unsigned i = 0; i < nrows; ++i)
matrix[i] = NULL;
try {
for (unsigned i = 0; i < nrows; ++i)
matrix[i] = new Fred[ ncols[i] ];
for (unsigned i = 0; i < nrows; ++i) {
for (unsigned j = 0; j < ncols[i]; ++j) {
someFunction(matrix[i][j]);
}
}
if (today == "Tuesday" && moon.isFull()) {
for (unsigned i = nrows; i > 0; --i)
delete[] matrix[i-1];
delete[] matrix;
return;
}
...code that fiddles with the matrix...
}
catch (...) {
for (unsigned i = nrows; i > 0; --i)
delete[] matrix[i-1];
delete[] matrix;
throw; // Re-throw the current exception
}
for (unsigned i = nrows; i > 0; --i)
delete[] matrix[i-1];
delete[] matrix;
}
为什么我们要使用删除这种方式,我的意思是,
首先delete[] matrix[i-1];
然后delete[] matrix;
此外,整个“try ... catch”循环之后有什么意义呢,我们还是要把
for (unsigned i = nrows; i > 0; --i)
delete[] matrix[i-1];
delete[] matrix;
在此功能的结尾。
这段代码实际上是关于一个很好的例子,什么例外的是,他们都没有,和如何使用它们的内容:异常信号异常情况,它们是*不*错误代码。 –