在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;
在此功能的結尾。
這段代碼實際上是關於一個很好的例子,什麼例外的是,他們都沒有,和如何使用它們的內容:異常信號異常情況,它們是*不*錯誤代碼。 –