What type does it->first give?

Viewed 91

Consider the following code:

  static std::unordered_map<std::string, Info> stringCollection;

  auto& [it, inserted] = stringCollection.try_emplace(pString);
  if (inserted) {
    it->second.str = &it->first;
  }
  return it->second;

This line it->second.str = &it->first is supposed to copy the address of the key (pointer) - but I cannot seem to verify if this will be the case (cannot find reference). Basicly does it->first give me a copy or reference ?

2 Answers

You want to remove the & after auto because try_emplace does not return references:

auto [it, inserted] = stringCollection.try_emplace(pString);

In this case, the type of it is std::unordered_map<std::string, Info>::iterator which satisfies LegacyForwardIterator which implies LegacyInputIterator:

  • it->m is equivalent to (*it).m;
  • *it returns std::iterator_traits<It>::reference (where It is the type of it).

So the type of *it in your case is std::pair<const std::string, Info>& (a reference), so if you access its member first, you get a reference to a const std::string as you expect.

The iterator holds the key/value pair. So ->first will give a an std::string as reference

Related