c++ - 充满垃圾记录的 map

标签 c++ stl

我正在使用这样的 map :

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 );
}

...

添加到 map :

m_mUsers[ sd ] = pUser;

从 map 中删除:

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

当我运行它时,它大部分都按我预期的那样工作。但很少有垃圾记录留在 map 中,所以当我尝试遍历预期为空 map 的内容时,我遇到了垃圾记录,并在 i->second->GetUserID() 上崩溃...什么我做错了吗?

最佳答案

您没有检查 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 );
}

这应该能让代码正常工作。顺便说一句,我建议你使用 std::shared_ptrstd::unique_ptr 用于 map 的 mapped_type。 如果你没有可用的 c++11,你可以尝试 technical reportboost libraries , 其中包括智能指针。 如果你只是想有一个引用而不关心管理 std::map 中的 CUser, 你也可以这样做,这意味着你没有为 CUser 管理内存(仅在 c++11 中):

//No room for the question: Who is managing CUser memory in this map?
std::map<int, std::reference_wrapper<CUser>> m_mUsers;

如果您不修改用户,您甚至可以这样做:

//Note I added const to CUser
std::map<int, std::reference_wrapper<CUser const>> m_mUsers;

关于c++ - 充满垃圾记录的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15546344/

相关文章:

c++ - OpenCV/FFMpeg图像捕捉问题

c++ - 与以空结尾的字符串相比,std::string 的效率如何?

C++ 抽象类作为 std::map 键

c++ - 我在具有 equal_range 的字符串 vector 中找到所有包含五个字母的单词,并且它不断抛出一个错误,说它没有排序

Java 和 SWIG : class into a package

c++ - 'U' 不指代一个值

时间:2018-01-08 标签:c++cuda: cudaMallocManaged access outside of constructor

c++ - Win32 消息泵与 MFC 消息映射,哪个更快? C++

c++ - 无法在 STL 中打印一组 vector 的元素

c++ - 填充字符串 vector