logoalt Hacker News

themafiayesterday at 1:49 PM1 replyview on HN

Ah, and because this is C++, the standard map having typed template parameters, which could be a non pointer, they're forced to make operator[] have this semantic:

Returns a reference to the value that is mapped to a key equivalent to key or x respectively, performing an insertion if such key does not already exist.

Which is a bit of a surprise coming from mostly C and Go.


Replies

ahartmetzyesterday at 4:10 PM

This "create a default-constructed value just so you can return a reference" logic is pretty terrible tbh. For insert: first create a default-constructed value, then assign to it. For retrieval: in the not found case, (permanently) insert a default-constructed value into the map. Need to return a valid reference!

Qt containers do it better: upsert with insert() and retrieve with value(), which, in the not found case, will return a default-constructed value (or a caller-supplied value) but without inserting it into the map.