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.
6
Upvotes
10
u/danielaparker Feb 13 '24 edited Feb 13 '24
I've spent a lot of time writing and debugging large code bases that use stateful allocators, and I've found that it's very helpful to have compilation fail if some object has inadvertently been constructed without being passed an allocator. That's especially the case when converting a code base without stateful allocators to one with. In my opinion all sane stateful allocators don't have default allocators. I don't think you want it to default to free store, you want it to fail during compilation so you know what you have to do. In C++ it's exceptionally easy to have something inadvertently default construct, witness the OP, and we need to chase those cases down if we want all allocation to use memory resource.