【发布时间】:2013-03-31 09:04:36
【问题描述】:
有一个映射,它将int 映射到Test*。
所有Test* 指针都在之前分配,然后分配给映射。然后,我将 deleteing 映射的值设置为 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 ** //
}
我想,当我在循环中deleteing 他们时,我错过了一些东西。
如何解决?
第二个问题是,deletes 分配的指针是否正确?
【问题讨论】: