Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's safe to return address of a std::map value?

Tags:

map

stl

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);
}
like image 739
panait.distrati Avatar asked Aug 31 '12 12:08

panait.distrati


People also ask

What does map at return?

map::at() at() function is used to reference the element mapped to the key value given as the parameter to the function. For example, if we have a string “hi” mapped to an integer 1, then passing the integer 1 as the parameter of at() function will return the string “hi”.

What is std::map used for?

If you mean std::map , it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value.

What does map Find return if nothing is found C++?

Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().

What does std::map return if key not found?

std::map operator[] inserts the default constructed value type in to the map if the key provided for the lookup doesn't exist. So you will get an empty string as the result of the lookup.


2 Answers

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

like image 198
Alok Save Avatar answered Oct 18 '22 20:10

Alok Save


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.

like image 38
rano Avatar answered Oct 18 '22 21:10

rano