从映射中删除指针
Delete pointers from a map
有一个映射int
到Test*
的映射。所有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|+-----+
变量x
是NULL
,但是变量one
仍然指向对象。如果对象已被删除,则取消引用该指针将导致未定义的行为。
删除所有内容的最简单方法是:
qDeleteAll(map);
相关文章:
- 使用函数引用指向节点的指针删除链表中的节点?
- 如何通过指向元组的共享指针删除对象
- 函数内的 C++ 指针删除
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 如何通过存储在 std::list 中的指针删除对象?
- C++中的智能指针删除
- 将C 中的每个指针删除作为阵列的指针安全吗?
- 使用 C 字符串和指针.删除除小写和空格以外的任何字符
- 在特定情况下,指针删除和铸造之间的关系不清楚
- 提升属性树:使用指向节点及其父节点的指针删除节点
- 警告C4150在尝试包装本机C 类时,指向不完整类型的指针删除
- C++ Valgrind 双指针删除,用于防止内存泄漏
- C 通过指向其基类的指针删除派生对象
- 将指针删除到数组
- 当通过其中一个指针删除对象时,C++将所有指针设置为null
- 智能指针删除器和"using"名称为"pointer"关键字
- 通过指向其基的指针删除 POD 对象是否安全
- 模板化的出列无效指针:删除类时失败
- 使用"this"指针删除
- (C++) list.error 方法和使用指针删除内存