9 ms·
Unfortunately while C++ does distinguish between things which can appear on the left hand side and right hand side of assignment, the things that can go on the
by plorkyeran 4y ago
Unfortunately while C++ does distinguish between things which can appear on the left hand side and right hand side of assignment, the things that can go on the lhs are much broader than in most programming languages. For example, a pretty normal thing to write in C++ is `foo(map) = 1;`, where foo something like `int& foo(std::map<std::string, int>& map) { return map["key"]; }`.
The ability to compute and pass around lvalue references (where "lvalues" are approximately "things that can appear on the lhs of assignment") is a very powerful feature, but also one which causes complexity in all sorts of other places, which is a bit of a theme for C++. One of those complexities is that non-const `operator[]` essentially has to be `operator[]=` even if at this specific call site there's no assignment happening.
C++ could have had const `std::map:::operator[]` throw an exception if the key isn't present, but having const and non-const versions of a function do different things is extremely error-prone and instead you have to use at() if that's what you want.