map::operator[] should be nodiscard

quuxplusone.github.io

84 points by jandeboevrie 4 months ago


junon - 3 months ago

For the Rust inclined, [[nodiscard]] is #[must_use], if you were confused.

Anyway, this article illustrates a great reason why C++ is a beautiful mess. You can do almost anything with it, and that comes at a cost. It's the polar opposite ethos of "there should be one clear way to do something" and this sort of thing reminds me why I have replaced all of my systems language needs with Rust at this point, despite having a very long love/hate relationship with both C and C++.

Totally agree it should be marked as nodiscard, and the reasoning for not doing so is a good example of why other languages are taking over.

nialv7 - 3 months ago

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

reactordev - 3 months ago

My pet peeve with c++ is exactly this. Either it’s not wise to call release, or it is (under circumstances) and yet the developer has no idea whether their scenario applies (tip: it doesn’t, 90% of the time).

The stdlib is so bloated with these “Looks good, but wait” logic bombs.

I wish someone would just draw a line in the sand and say “No, from here on out, this is how this works and there are no other scenarios in which there needs a work around”. This is why other systems languages are taking off (besides the expressiveness or memory safety bandwagon) is because there are clear instructions in the docs on what this does with examples of how to use it properly.

Most c++ codebases I’ve seen the last 10 years are decent (a few are superb) and I get that there’s old code out there but at what point do we let old dogs die?