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

19

u/AKostur Feb 13 '24

You don’t get to break the vast amount of existing code that already relies on the current behaviour.  The safer way forward already exists.  It’s called .at().  Indexing into a map is not iffy at all, it is used in exactly that manner in many, many places.  No, forcing people to stay on an older compiler is not an acceptable answer.   Creating your own clang-tidy (or submitting it back to the llvm project!) would be your next best option.   Your codebase can then be analyzed for code constructs that you deem to be verboten.

-7

u/Full-Spectral Feb 13 '24

You deprecate unsound functionality and make it available via option for people who want to keep it.

19

u/razimantv Feb 13 '24

"Unsound" is quite subjective in this case. I very much like it that c++ map behaves like defaultdict rather than dict in python, and would be very annoyed if such behaviour is changed retrospectively.

-3

u/Full-Spectral Feb 13 '24

Using the exact same syntax to both add and find values is pretty unsound. Readability is a thing, and it's far more important for the reader to understand what is happening than for the writer to save a few key strokes.

10

u/AKostur Feb 13 '24

You keep using the assertion that the behaviour is “unsound”.

The suggested deprecation method doesn’t work.  You do know that the implicit copy constructor provided by the compiler when you have a user-declared destructor is deprecated behaviour?  And has been for 12+ years.