例如,我有一個Library類,它爲不同的內容集合保存了一個ptrs數組。如何正確刪除一個ptrs數組?我的析構函數似乎缺少實際的對象
ContentCollection** contents;
但我的刪除似乎無法擊中實際的集合(在這種情況下是樹)。
Library::~Library() {
//Delete stored ContentCollections
for (int i = 0; i < POTENTIALCONTENTTYPES; i++) {
delete contents[i];
contents[i] = NULL;
}
delete[] contents;
}
這裏是以防萬一我犯了一個大錯誤樹上的析構函數:
ContentCollection::~ContentCollection() {
deleteHelper(root); //Deletes Contents
}
//-----------------------------------------------------------------------------
//Deletes stored Contents
void ContentCollection::deleteHelper(Node* curr) {
if (curr != NULL) {
deleteHelper(curr->left);
deleteHelper(curr->right);
delete curr->data;
curr->data = NULL;
delete curr;
}
}
我很明顯地做錯事,近無我的記憶中被釋放。
爲什麼* everything *指針? – chris
如果你有一個指針數組,你可以走數組並且說:'free(ptr)',然後在數組走完之後,你可以說:'free(array_ptr);' – Fallenreaper
@Fallenreaper,不''free', 'delete'。 'free'是用'malloc'分配的內存(我真的希望沒有使用它)。 – chris