gpt4 book ai didi

c++ - 从 map 中删除指针

转载 作者:太空宇宙 更新时间:2023-11-04 15:46:36 25 4
gpt4 key购买 nike

有一个映射将 int 映射到 Test*。所有 Test* 指针都在分配给映射之前分配。然后,它删除 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 ** //
}

我想,当我在循环中deleteing 时,我错过了一些东西。如何修复?

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

最佳答案

在循环中,变量x 只是循环内部的局部指针。当您将其设置为 NULL 时,您实际上并未将任何 other 指针设置为 NULL

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

*itr = nullptr;

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


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

+-----+| one | ---\+-----+     |     +---------------+             >--> | Test instance |+-----+     |     +---------------+|  x  | ---/+-----+

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

+-----+| one | ---\+-----+     |     +---------------+             >--> | Test instance |+-----+           +---------------+|  x  | +-----+

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

关于c++ - 从 map 中删除指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15727958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com