logoalt Hacker News

nialv7yesterday at 5:30 PM2 repliesview on HN

C++ operator [] is poorly designed: index, and index+assignment should be two different operators, and indexing alone should never insert new entries into the map.

Languages like D [0] or Rust [1] get this right.

[0]: https://dlang.org/spec/operatoroverloading.html#index_assign... [1]: https://doc.rust-lang.org/std/ops/trait.IndexMut.html


Replies

gpderettayesterday at 6:33 PM

You could (and I would) make the opposite statement: upsert should be the default operator and if you want lookup only or insert only you call different operators.

I find it annoying that I often have to reach to defaultdict in Python to get this behavior.

show 2 replies
Tempest1981yesterday at 11:40 PM

iirc, there are 5 ways to put something into a std::map

  operator[], insert(), emplace(), try_emplace(), insert_or_assign()
And 2 of them don't overwrite an existing value.

Lots of people are surprised that insert() can fail. And even more surprised that a RHS [] inserts a default value. I'm not a fan of APIs that surprise.