std::map
in a single thread.operator[]
for some keys; these keys are guaranteed to have been inserted in the first step. (No other thread will attempt to modify the map either.)Therefore, no multithreaded insert should occur.
Is this guaranteed to be thread-safe (won't lead to any data races etc) rather than just probably thread-safe due to []
being easy to implement with find+check+insert?
I know that in such a case, find
or at
should be used instead as there's no benefit to []
and it misleads about the intended logic. I'm just wondering if such a design mistake can cause errors.
To sum up the discussion in comments:
This part of the standard guarantees that const member functions of STL classes satisfy my requirement. Non-const member functions are not guaranteed to do so, e.g. some implementation of std::unordered_map
may rehash if lookup is performed using operator[]
. Therefore they must not be used in multithreaded applications without synchronisation.
In general, there's no guarantee that const
member functions of any class don't modify shared data. This has to be stated explicitly. The link above states it only for standard library functions.