2014-03-12 9 views
0

例如,我有一個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; 
    } 
} 

我很明顯地做錯事,近無我的記憶中被釋放。

+0

爲什麼* everything *指針? – chris

+0

如果你有一個指針數組,你可以走數組並且說:'free(ptr)',然後在數組走完之後,你可以說:'free(array_ptr);' – Fallenreaper

+0

@Fallenreaper,不''free', 'delete'。 'free'是用'malloc'分配的內存(我真的希望沒有使用它)。 – chris

回答

2

用替換std::vector<std::unique_ptr<ContentCollection>>,你就不用擔心delete了。

我認爲ContentCollection是一個抽象基類?然後destructor需要是虛擬的。否則,你可以拋棄一個間接級別並使用std::vector<ContentCollection>

+0

我希望避免使用矢量,因爲需要攜帶迭代器。我想避免回去並在所有需要的地方更改設計...... ContentCollection僅僅是一個抽象地命名的BST。 –

+0

@MilanNovaković,你可以考慮把'ContentCollection'設爲[多]集。這幾乎是BST,但效率更高。不過,我不確定迭代器是如何影響你的。 'std :: vector'的隨機訪問迭代器可以像指針一樣使用。事實上,他們可能*是指針。 – chris

+0

如果你不需要使用迭代器,他們不會花費任何東西。 – fredoverflow

相關問題