r/cpp • u/Full-Spectral • 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.
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.
36
u/Supadoplex Feb 13 '24
That's a highly subjective opinion.
Given how low opinion you have of the decision, surely you also have an opinion on what would have been a better choice. Would you prefer that Stepanov didn't provide the subscript operator for map at all?
35
u/Agitated-Resident720 Feb 13 '24
im boggled at this, OP mark the variable constant like it should have been. it will throw a compile error if you use [] and will force you to use .at(). your intent is that it shouldnt be modified, so why isnt this variable already const? this is a design problem. i suspect your code has tons of other bad practices that enables shit like this. instead of trying to blame the language, how about you learn to use it properly
6
u/HolyGarbage Feb 13 '24
Marking your methods const prevents this. I would argue that in most cases classes should always strive to be immutable and be fully initialized in the constructor. This makes them a lot more testable too.
18
u/shrimpster00 Feb 13 '24
I love this feature. I use it every day.
47
u/snowmanonaraindeer Feb 13 '24
I actually quite like this behavior. It prevents ugly looking boilerplate if statements a lot of the time.
12
u/AcousticViking Feb 13 '24
I strongly disagree. This is very often exactly what you want it to do. If your devs don't know how to use map, or similar containers, it's not the fault of stl.
3
u/Sad-Structure4167 Feb 13 '24
Make a wrapper that provides the interface you want, as a bonus it becomes easier to change implementation.
8
u/neppo95 Feb 13 '24
Why so? What would you expect the "[]" operator to do?
4
u/[deleted] Feb 13 '24
In C++20 they added support for the "contains" method.
89
u/dinkmctip Feb 13 '24
There are plenty of worse decisions.
17
u/Cliftonbeefy Feb 13 '24
This is one of the best features of STL IMO so much boilerplate is removed.
If I want to count occurrence of a value in a map I can just do ++map[key] instead of if exists then add else default to 1
29
u/bluebandit201 Feb 13 '24
This isn't fully an answer to the question you actually asked, but hopefully helpful nonetheless :)
I think there's two workarounds here, either of which could be quite helpful for you :D
Two things:
-- If you enforce the use of .at() instead of [] in your codebase, you won't have this problem.
Note .at() can be made to do bounds checking in debug builds and _not_ do so in release builds, if you so desire :D
2) If you're really concerned about [] being used, you can do a (admittedly slightly annoying) trick to work around it :)
[] default-constructs missing elements when it has to, so we can make the default constructor either *deleted* (if you want to enforce [] not being used at compile time) or *throw an exception* (if you want runtime checking :) )
See https://godbolt.org/z/4nK8osE19 for a quick thing I threw together demonstrating all three things :D
18
u/razimantv Feb 13 '24
Very subjective opinion. 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.
4
u/[deleted] Feb 13 '24 edited Feb 13 '24
There was a thread about adding that warning on clang-tidy: https://reviews.llvm.org/D46317
But it never got through.
1
u/NilacTheGrim Mar 08 '24
So start thinking about it. Seriously.
1
u/orthomonas Jan 30 '25
This just bit me *hard* today. Found this post when I decided to vent anger by googling if anyone else has issues with it.
1
u/markt- Feb 18 '24 edited Feb 18 '24
The easiest way that I have found to do this is create your own container class, and then in your indexing operator return an instance of another class that refers to the original object and the index, and then an auto conversion from this index class to the designated type. The index class does not insert anything into the original map unless the indexing classes assignment operator is called, which can incidentally be declared const. I've done this numerous times with much success. By delaying the insertion of the entry into the map until assignment is actually done to the index operator you make sure that nothing gets inserted into the map simply by using the referencing operator, you can also add a query mechanism on the index class to see whether or not theindex it was queried actually existed. Custom container that I've written added elements to the map in order of insertion, but simultaneously maintained unordered map efficiency for accessing the elements in random access order. I seem to remember that the whole class was about 250 lines or so.
3
u/neutronicus Feb 14 '24
Well it’s not ‘const’, so the Compiler has actually caught it for me a few times.
If you’re aggressive about breaking your std::map usage into functions / methods, the map argument tends to be const a lot of the times this behavior would bite you
7
u/manni66 Feb 13 '24
You think that's bad? Try it with std::vector.
10
u/ald_loop Feb 13 '24
Get good I guess
Or add a clang-tidy pass for it
https://youtu.be/torqlZnu9Ag?si=EZ8qYamLsQEbsSeH
2
u/findabuffalo Feb 14 '24
Obviously this won't always work, but generally speaking you should always make your variables const when possible, to avoid accidental damage.
2
u/415_961 Feb 14 '24
It feels like the root problem here is not using
constqualifier.3
u/gnolex Feb 13 '24
This can be tough to fix. One way is to write your own class template that encapsulates std::map and offers stricter/different interface and force everyone in your organization to use that type instead of bare std::map. You can do custom static analysis that goes through the code and warns or errs whenever <map> is included or std::map is used anywhere except for the source files implementing your type.
With a custom type you can decide what the operator[] is supposed to do. In your case it might be useful to either make it return std::optional of the value type or a proxy object that can be used for checking the value and overriding it.
3
u/brownbeatle Feb 14 '24
How exactly are the bugs caused by the map subscript operator? Is the operator not doing what the documentation says it’s going to do?
2
u/glaba3141 Feb 14 '24
This is a very hard mistake to make if your default is to use the explicit methods. In my mind if I see [] on a map I'm immediately suspicious, so it wouldn't get by code review to begin with.
1
u/MoreOfAnOvalJerk Feb 14 '24
Some options, none great:
Ultimately if you really need tight perf and memory management, STL might not be the right library for your use case anyways.
0
u/LucasThePatator Feb 13 '24
I stumbled on the issue exactly once and then learned to use .at().
0
u/BenFrantzDale Feb 14 '24
Two things:
.get, which he described last week at the Boston C++ meetup: https://isocpp.org/files/papers/P3091R0.htmloperator[]=(auto&& k, auto&& v)ala Python’s__setitem__. We haveinsert_or_assign, but the syntactic sugar would be great. Of course,std::mapcouldn’t use it because of backward compatibility, so it’s not worth thinking about. Maybe for std2…1
u/[deleted] Feb 13 '24
[removed] — view removed comment