简体   繁体   中英

C++ std::unordered_map

I am am using std::unordered_map and I would like to use it to store pointers to an object that I dynamically create with new .

I can create the objects fine and the insert method succeeds; however when I attempt to resolve a specific object from the map using the index it appears that all of the items in the list are mapped to the last item I point in the map.

typedef std::unordered_map<__int64, Session*> HashDict;
HashDict dict;

void Sessions::Insert()
{
  Session* newSession = new Session;
  newSession->setId(sessionCounter++);
  dict.insert(HashDict::value_type(newSession->Id(), newSession));
}

void Sessions::Find(__int64 id)
{
  HashDict::iterator it = dict.find(id);

  if(it != dict.end())
  {
    Session* s = it->second;
    std::cout << "Search for: " << id << std::setw(3) << 
                 " found @ location: "  << it->second << std::setw(3) << 
                 " with value: " <<  s->Id() << std::endl;
  }
}

001D4F50    0
001D5038    1
001D50D0    2
001D5378    3
001D5410    4
001D54A8    5
001D5540    6
001D55D8    7
001D5670    8
001D4E50    9
Search for: 5 found @ location: 001D54A8 with value: 9

Notice that 5 points to the location at 5 (from the insert), however it says that the value is 9 .

What am I doing wrong?

If I had to guess from the output you're getting, by any chance is the ID field of Session marked static? If so, this would manifest itself with exactly the behavior you're seeing here. In particular, if the field is static, then every time you create and update the ID of a new session, you'd be overwriting the ID field shared across all Session objects and only the last Session ID would persist.

If I'm totally wrong, let me know and I'll delete this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM