I have a std::multimap that maps session IDs (ints) to the pieces of hardware used in that session (the hardware is described by a struct that contains some hardware specific info).
I have a cleanup function that has to do specific cleanup stuff for each piece of hardware. After the cleanup is done, I need to erase that element from the map, since the hardware is no longer used in that session.
Note that I don't just want to remove a single piece of hardware from a session. Instead the whole session gets torn down, so I want to search the map for the session ID, cleanup the hardware, and remove all those entries from the map.
Here's some code which shows what I am trying to explain:
void MyClass::end_session(const int session_id) {
// session_map_ is a member variable of MyClass
const auto range = session_map_.equal_range(session_id);
for (auto it = range.first; it != range.second; session_map_.erase(it++)) {
// do cleanup for the hardware pointed to by it->second
}
}
Is the loop legal? I know that the iterator passed in to erase() gets invalidated, but this doesn't invalidate range.first or range.second, correct? Also, does session_map_.erase(it++) work like I would expect it to? That is, I'm assuming that it gets saved as the argument for erase(), gets incremented to its new value, and then erase() is called for the old value (thus invalidating the iterator before the increment). Is that correct?
Aucun commentaire:
Enregistrer un commentaire