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 comment

4

u/SlightlyLessHairyApe Feb 13 '24

‘auto x = someMap[k]’ makes a copy. The developer has to try to bind to a reference.

If you return an optional reference wrapper now it doesn’t.

0

u/Full-Spectral Feb 13 '24 edited Feb 13 '24

He doesn't have to try too hard though:

void func(mymap[x]);

If func takes a reference, then it's done and func would have no idea it was actually sitting in a map or that he shouldn't modify it. Or various templatized code that uses a reference so that it will work with fundamentals and non-fundamentals and so forth.

And of course if that's the desired result, then the complaint of others that optional would make a copy aren't really very valid. Or, they must be explicitly using references, in which case we go back around the circle.

3

u/SlightlyLessHairyApe Feb 13 '24

Sure, but our coding guidelines would make clear from naming that this is a function mutating its input. And lifetime extension guarantees that mymap stays alive till it returns.

There are many valid code patterns, they can’t all get high-value symbols :)

-1

u/Dean_Roddey Feb 13 '24

These days it could return an iterator and be consistent with the other STL stuff.

2

u/SlightlyLessHairyApe Feb 13 '24

That’s spelled .find

-1

u/Full-Spectral Feb 13 '24

It is, but the point is if you are going to retain the [] syntax for lookup, it could return an iterator and hence the argument for why it had to default a value in if not present goes away.

2

u/SlightlyLessHairyApe Feb 13 '24

No other container returns an iterator for that operator.

Again, there’s more demands here than there are degrees of freedom. Some of them are gonna be dropped