In my opinion it's best not to return pointers to the contents of a map that you're keeping private since the pointers may be invalidated if the map changes.
I would have the function return a success code (bool
) and pass a reference to a string to actually return the value in if found. For example,
bool get_tag_value(const string& tag, string& value)
{
auto t = my_map.find(tag);
if (t == my_map.end()) return false;
value = t->second;
return true;
}
Note that while unordered_map::at()
will throw if the key is not found, unordered_map::find()
returns an invalid iterator (unordered_map::end()
) - so you can avoid handling exceptions this way.
If you want to stick with returning a string, then simply return an empty string (return string();
) if the key isn't found.