マップがあり、 を にマップしint
ますTest*
。
すべてのTest*
ポインターはマップの前に割り当てられ、後でマップに割り当てられます。次に、map の値をdelete
ingnull
して に設定します。
その後、 の有効性をチェックし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
ループでそれらを実行しているときに、何かを見逃したと思います。
どうすれば修正できますか?
2 番目の質問は、割り当てられたポインターが正しいかどうかですdelete
。