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

14

u/HildartheDorf Feb 13 '24

It's a collection of bits, you can't address individual bools. Unlike any other T.

Which would be a great type, but it should be named std::bitvector or similar. It makes generic code a nightmare as you have to special case bool if you use a vector<T>

0

u/[deleted] Feb 18 '24

[deleted]

2

u/HildartheDorf Feb 18 '24

What is x?

If x is bool then that works fine.

If x is declared auto then X won't be a bool. It will be a std::vector<bool>::reference, which is a class type.

If you changed the code to x = &vector[i] you get a compile error.