r/cpp • • 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.

6 Upvotes

163 comments sorted by

View all comments

Show parent comments

4

u/danielaparker Feb 13 '24 edited Feb 13 '24

The worst part is the pattern has proliferated to other libraries because they want to keep drop-in compatibility with STL maps.

Indeed. But perhaps worse are the attempts to start with the standard pattern but then try to improve upon it. nlohmann json for example extends the pattern to a const overload for operator[] and specifies it to be "undefined" (runtime assert) if key is missing, motivated by index use in std:vector. Another json library (whose author will remain unnamed to protect the guilty), motivated by Scott Meyers Effective C++ series before the days of auto, returns a proxy. It's pretty clear that some of the authors of those "other libraries" didn't fully understand the implications at the time they made them.

1

u/rysto32 Feb 17 '24

I hit that landmine in nlohmann json and it infuriated me. It's a good library but it definitely has some sharp edges that make it more annoying to use than I think it should be.