1

我正在使用这样的地图:

map<int,CUser*> m_mUsers;

...

for ( i = m_mUsers.begin(); i != m_mUsers.end(); i++ )
{
    if( (*i).second->GetUserID() == pUser->GetUserID() )
        (*i).second->OnDeviceLogout( pUser );
}

...

添加到地图:

m_mUsers[ sd ] = pUser;

从地图中删除:

i = m_mUsers.find( sd );
m_mUsers.erase( i );

当我运行它时,大多数情况下它都按我的预期工作。但是很少会在地图中留下垃圾记录,因此当我尝试遍历预期为空的地图时,我遇到了垃圾记录,并在 i->second->GetUserID() 上崩溃...什么我做错了吗?

4

1 回答 1

0

您没有检查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 CUsers in the std::map, you can also do this, which implies you are not managing memory for CUsers (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;
于 2013-03-28T06:11:27.890 回答