7

I have a std::map<std::string, myStruct>. It's safe to return address of a myStruct entry ?
I am sure that my entry will not be removed, but other entries can be added.

Type::iterator it = m_map.find(key);

if (it != m_map.end())
{
     return &(it->second);
}
panait.distrati
  • 138
  • 1
  • 6
  • A variant on this question is if the contract for std::map indicates that the address of the "second" element will remain the same even when elements are added or removed from the map. That would be unlike std::vector where the array elements are moved around in memory.. I have a use case where I could take the address of the map entrues and put the pointers to the elements in an a map with a different ordering – peterk Feb 15 '19 at 04:19

2 Answers2

8

It is safe.
In case of std::map only iterators/references/pointers to removed elements are invalidated.

Reference:
C++03 Standard 23.1.2/8:

Only iterators and references to the erased elements are invalidated

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

It is an address of the contained object not about the container's allocated space in it.

By the way, try to explain what are you trying to do and what is your goal, so we can be more helpful.

rano
  • 5,616
  • 4
  • 40
  • 66
  • `it->second` should point to the value so `&(it->second)` it is address of that object. I need to check in that map for a value and return it to caller but somehow handle the case that entry does not exist (in this case I will return NULL). I don't use boost in that project so, I cannot use `boost::optional`. – panait.distrati Aug 31 '12 at 12:35
  • In this case your code shall be fine. Keep in mind that each operation you later do on that struct will be represented in the map too since you are passing it by address (and not by value) – rano Aug 31 '12 at 12:39