从映射中删除指针

Delete pointers from a map

本文关键字:指针 删除 映射      更新时间:2023-10-16

有一个映射intTest*的映射。所有Test*指针都是在分配给映射之前分配的。然后,它delete的映射指针并将它们设置为null。之后,它检查one的有效性,并且它应该是null但是one不是null

#include <QString>
#include <QMap>
#include <QDebug>
class Test {
    QString name;
public:
    Test(const QString &name) : name(name) {}
    QString getName() const { return name; }
};
int main() {
    QMap<int, Test*> map;
    Test *one = new Test("one");
    Test *two = new Test("two");
    Test *three = new Test("three");
    map.insert(1, one);
    map.insert(2, two);
    map.insert(3, three);
    for (auto itr = map.begin(); itr != map.end(); itr++) {
        Test *x = *itr;
        if (x) {
            delete x;
            x = 0; // ** Sets null to the pointer ** //
        }
    }
    if (one) // ** Here one is not 0 ?! ** //
        qDebug() << one->getName() << endl; // ** And then here crashes ** //
}

我想,当delete在循环中对它们进行时,我错过了一些东西。如何修复?

第二个问题是,它是否正确地delete分配的指针?

在循环中,变量x只是循环内部的本地指针。当您将其设置为NULL时,实际上并没有将任何其他指针设置为NULL

您应该将迭代器取消引用返回的引用设置为NULL:

*itr = nullptr;

这将使映射中的指针为NULL,但其他指针仍将指向现在已释放的内存区域。


当你有两个指针时,它看起来像这样:

+-----+|一个|---\+-----+|+---------------+>-->|测试实例|+-----+|+---------------+|x|---/+-----+

如果你设置一个指针,它看起来像这样:

+-----+|一个|---\+-----+|+---------------+>-->|测试实例|+-----++---------------+|x|+-----+

变量xNULL,但是变量one仍然指向对象。如果对象已被删除,则取消引用该指针将导致未定义的行为

删除所有内容的最简单方法是:

qDeleteAll(map);