c++ - How to properly delete a map of pointers as key? -
i have map of key/value pointers :
std::map<a*, b*> mymap;
what proper way liberate memory of key only?
i thinking doing :
for (auto itr = _mymap.begin(); itr != _mymap.end(); itr++) { if (certaincondition == true) { delete itr->first; itr->first = nullptr; } }
is correct way of doing it? map keep nullptr
key , future iteration include nullptr
?
you cannot modify key of container because used define ordering , changing in place invalidate ordering. furthermore, each key needs unique. therefore, need remove item map clean memory.
if have key:
mymap.erase(key); delete key;
if have iterator within map:
a* keycopy = itr->first; mymap.erase(itr); delete keycopy;
edit
per updated question:
auto itr = mymap.begin(); while (itr != mymap.end()) { if (certaincondition == true) { a* keycopy = itr->first; itr = mymap.erase(itr); delete keycopy; } else { ++itr; } }
Comments
Post a Comment