您没有检查i != m_mUsers.end()
. 这是不正确的,除非保证sd
在您的情况下存在。
i = m_mUsers.find( sd );
//You should do the check before erasing
if (i != m_mUsers.end()) {
m_mUsers.erase( i );
}
That should make the code work correctly. By the way, I recommend you use
std::shared_ptr
or std::unique_ptr
for the mapped_type
of the map.
If you don't have c++11 available, you can try technical report or boost libraries,
which include smart pointers.
If you just want to have a reference and don't care about managing CUser
s in the std::map
,
you can also do this, which implies you are not managing memory for CUser
s (in c++11 only):
//No room for the question: Who is managing CUser memory in this map?
std::map<int, std::reference_wrapper<CUser>> m_mUsers;
And if you don't modify users, you can do even this:
//Note I added const to CUser
std::map<int, std::reference_wrapper<CUser const>> m_mUsers;