例如,我有一个库类,它包含指向不同内容集合的指针数组。
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;
}
}
我很明显做错了什么,因为我的内存几乎没有被释放。
最佳答案
替换ContentCollection**
通过 std::vector<std::unique_ptr<ContentCollection>>
, 你不必担心 delete
s 了。
我假设 ContentCollection
是抽象基类?然后 destructor
需要是虚拟的。否则,您可以放弃一级间接寻址并使用 std::vector<ContentCollection>
.
关于c++ - 如何正确删除一个指针数组?我的析构函数似乎缺少实际对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22358768/