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);
}
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”.
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.
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().
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With