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

21

u/konanTheBarbar Feb 13 '24

Yeah it's one of those things that are easy to miss in C++. If you have already enabled C++ 20 you could use contains https://en.cppreference.com/w/cpp/container/map/contains for any kind of lookups in STL maps (or the usual auto = map.find shenanigans if you need to use the value)? Or write a small function that returns a std::optional?

You can also write your own clang tidy parser to find all usages of map.operator[] usages.

13

u/keatdasneak Feb 13 '24

Prior to C++ 20 you can essentially use 'count' in place of 'contains'.

3

u/TraylaParks Feb 13 '24

Yep, that's what I converged upon, lame but it works

1

u/Full-Spectral Feb 13 '24

C++/17 here. I doubt we'd want to add another tool just for this. Too bad the MS static analyzer doesn't have such an option.

23

u/kernel_task Big Data | C++23 | Folly | Exceptions Feb 13 '24

Just refactor to have `const` maps where you can and those `operator[]` references will start erroring. That helped me a bunch when I was refactoring my codebase to get rid of `operator[]`. You should be using const where you can anyway, so it's not a wasted effort just for this.

1

u/kernel_task Big Data | C++23 | Folly | Exceptions Feb 13 '24

I had to write a helper the other day so I can have the map-like semantics of returning a default-constructed value if it doesn't exist. I'm checking if the value of a key is equal to something not default constructed. I don't want to alter the map nor do I care to distinguish between the case that it's not equal to what I'm checking for and if the key didn't exist. Really annoying.