Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances can operator[] for std::map return 0?

Tags:

c++

c++11

llvm

I'm working with LLVM, and I'm having issues with the following piece of code that I did not write:

static std::map<std::string, Value*> NamedValues;
... //Lots of other code
Value *V = NamedValues["Demo string"];
return V ? V : ErrorV("V is not in NamedValues map.");

From what I understand of std::map, it should never return a null pointer (Unless it's out of memory?), so I have a hard time understanding how V being 0 would indicate that V is not in the map. As is, my program is always getting an error here, but I can't figure out why. Any help on what is going on here?

like image 629
Edward Marchioni Avatar asked Feb 08 '23 09:02

Edward Marchioni


1 Answers

std::map::operator [] returns a reference to the value if the key already exists, if the key does not exist, it inserts the key along with default-constructed value, and returns a reference to that value.

POD types (like pointers) have zero-initialization upon default construction. meaning that the pointer will have nullptr value if its default constructed.

if the key "Demo string" did not exist before calling NamedValues["Demo string"]; , the map will create a default constructed pointer as value, which will be constructed as nullptr.

if you want to find out if the map contains a key, you need to use find + end:

if (map.find(yourKey) != map.end()){
  //the key exists
}

EDIT:
as @ShadowRanger has pointed out, count can be used as well.

if (map.count(yourKey)){
   //the key exists
}
like image 140
David Haim Avatar answered Feb 16 '23 02:02

David Haim