Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a reference to an element inside an std::map be invalidated?

I have a multi-threaded application and a shared resource std::map<KeyType, ElementType>. I use a mutex to protect inserts, gets and removes.

My get method returns a reference to the stored element (unlocks on return), and then I do some work with that element.

Question: Is it possible that while working with the stored element reference, another thread may change the std::map so the element will be moved to a different address and the reference will no longer be valid? (I know there are certain ADT implementations which do rearrangement of the ADT on resize).

like image 545
Elad Weiss Avatar asked Nov 14 '17 07:11

Elad Weiss


People also ask

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.

Are std :: maps ordered?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare .

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.


1 Answers

The iterator invalidation rule for associative containers (which std::map is) says at [associative.reqmts]/9:

The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

So if one thread inserts an element, it won't affect any references to existing elements. But if it removes something, other threads may be borked. Some form of element-wise locking is in order, I'd say.

like image 134
StoryTeller - Unslander Monica Avatar answered Sep 20 '22 15:09

StoryTeller - Unslander Monica