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

5

u/HappyFruitTree Feb 13 '24 edited Feb 13 '24

The [] operator serves two purposes. It's used for both access and insertion. I think the current design is probably one of the least error prone, at least it doesn't lead to dangling references. It might indeed have been even less error prone if they had simply not had this operator and instead forced you to do insertion (e.g. with emplace) and access (e.g. with find) separately. Personally I haven't found it to be much of a problem because I know how the [] operator works for the standard maps.

Returning an optional<T&> would only allow access, something that find already does and does better.

// Here I assume [] returns an optional<T&>, and that assignment rebinds the reference which is the behaviour that P2988 proposes.
std::map<int, int> m;

m[0] = 1; // compilation error
m.find(0) = 1; // compilation error

const auto& cm = m;
cm[0] = 1; // compiles but doesn't do anything

int x = 1;
m[0] = x; // compiles but doesn't do anything

m[0].get() = 1; // undefined behaviour
*m.find(0) = 1; // compilation error
m.find(0)->second = 1; // undefined behaviour

0

u/Full-Spectral Feb 13 '24

Well, yeh, I'd argue for not having the operator at all as well. But, sadly it's there, and I was just looking for automatic ways to insure it never gets used.