c++ - 如何正确删除一个指针数组?我的析构函数似乎缺少实际对象

标签 c++ memory-leaks delete-operator

例如,我有一个库类,它包含指向不同内容集合的指针数组。

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/

相关文章:

c++ - 更新 : C++ undefined reference

C++ 错误 : expected type-specifier

c++ - 如何将二进制数据写入压缩文件

c++ - 使用C++中的Delete避免内存泄漏

c++ - qDeleteAll 和 new[]

c++ - 如何获得在 C++ 中生成字母表的更简单方法?

c++ - 插入队列期间内存泄漏

ios - iphone 应用程序中的内存泄漏 sqlite3MemMalloc

ios - ABPersonCopyImageData 泄漏

c++ - 为什么,真的,删除不完整的类型是未定义的行为?