Sunday, June 28, 2009

Surprise with std::map.operator [] and thread safety

A year ago or so, I got a surprise using std::map.operator [] in a multithreaded program -- the program kept crashing while in subscripting the map, even though I was just reading and nor writing -- I thought!

I looked it up today while peeking at my old code, and discovered that std::map.operator [] inserts a data_type() for the specific key if it does not exist -- which surely explains the crashes I got. The reason I was able to use it like this, was that I was storing a std::map to record valid pointers -- operator [] would thus return false for pointers that weren't keys in the map.

Lesson learnt? Use std::map.find() instead!

No comments:

Post a Comment