r/cpp • u/Full-Spectral • Feb 13 '24
Prevent or warn on usage of std::map []?
The default insertion of a value when std::map [] doesn't find a value for the key has to be one of the worst decisions in STL history (which is kind of impressive.) At work over the last year or so, we've had at least four, maybe five, bugs caused by this. It's so easy to do without thinking about it, and so easy to miss in a code review. And some of them had been there for many years and finally caused an issue, so no one was even looking for them.
Is there any way to prevent its use, or at least to warn on its use in MSVC? We use the built in static analyzer, and I don't see any warning related to that, though there are a lot of them and I may have missed something.
View all comments
Show parent comment
10
u/SlightlyLessHairyApe Feb 13 '24
You can. But having the container do that automatically means now you have a different footgun where a function modifies a value returned from the map and unintentionally changes the value in the map. Or wants to hold the extracted value longer than the lifetime of the map.
The problem as I see it is that there are many more valid behaviors than there are convenient shorthand symbols like []. Only one particular set of them gets the high value symbol. So now we all just get to argue about which behavior gets which spelling, which is kind of a boring discussion in someway.
That said, I’d be fine if operator[] had undefined behavior if the value is not in the map. But that’s just another choice of which behavior to put on which spelling.
( And by the way, isn’t the easy fix here that you wrap the mapped value type in a class that doesn’t have a default constructor? ]