c++ - map filled with junk records -


I am using the map like this:

  Maps & lt; Int, cUser * & gt; M_mUsers; (I = m_mUsers.begin (); i! = M_mUsers.end (); i ++) {if for   

...

  {if ((* *) .second-> GetUserID () == pUser- & gt; GetUASID ()) (* i) .second-> OnDeviceLogout (pUser); }   

...

Add to map:

  m_mUsers [sd] = pUser;   

Delete from map:

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

When I run it, mostly it works as I expected but very rarely, a junk record is left in the map, so when I expect to be a blank map , Then I go into the junk record, and I'm crashing at i-> second-> GetUserID (). What am i doing wrong

You i! = Not checking for M_mUsers.end () . This is wrong unless it is guaranteed that sd exists in your case.

  i = m_mUsers.find (sd); // You should check before deletion (i! = M_mUsers.end ()) {m_mUsers.erase (i); }   

This code should work properly, however, I recommend that you enter std :: shared_ptr or std :: unique_ptr mapped_type of the map for>. If you do not have C ++ 11 available, you can try it or include smart pointers. If you want just a reference and do not care about managing CUser s in std :: map , then you can do that too, which means that You are not managing storage for CUser s (in C ++ 11 only):

  // There is no room for the question: in this map CUser Who is managing the memory? Std :: map & lt; Int, std :: reference_wrapper & lt; CUser & gt; & Gt; M_mUsers;   

And if you do not modify users, you can also do this:

  // Note: I use the CUSAR std :: map & Lt; Int, std :: reference_wrapper & lt; CUser const & gt; & Gt; M_mUsers;    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -