有一张映射int到的地图Test*。所有Test*指针在分配给映射之前都已分配。然后,它delete是map的指针并将它们设置为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 ** //
}
Run Code Online (Sandbox Code Playgroud)
我想,我在循环中delete错过了一些东西。怎样才能修好呢?
delete第二个问题是,分配的指针是否正确?
在循环中,变量x只是循环内部的局部指针。当您将其设置为时,NULL您实际上并没有设置任何其他指针NULL。
您应该将通过取消引用迭代器返回的引用设置为NULL:
*itr = nullptr;
Run Code Online (Sandbox Code Playgroud)
这将使映射中的指针成为NULL,但其他指针仍指向现在已释放的内存区域。
当你有两个指针时,它看起来像这样:
+-----+
| 一| ----\
+-----+ | +----------------+
>--> | 测试实例|
+-----+ | +----------------+
| x| ---/
+-----+
如果您设置其中一个指针,它看起来像这样:
+-----+
| 一| ----\
+-----+ | +----------------+
>--> | 测试实例|
+-----+ +----------------+
| x|
+-----+
变量x是NULL,但变量one仍然指向对象。如果该对象已被删除,那么取消引用该指针将导致未定义的行为。