Closed miszak closed 2 years ago
Hello.
I am not familiar with internals of this library but I would like to write some comment about your problem. Some implementations of unordered maps store keys as non-const values. Doing that makes move operations faster (move constructor and move assignment operator). Suppose that class Boxed
from your example is very, very expensive to copy (for example just add some std::vector
inside). If robin_hood::unordered_map
had stored keys as const values then every reallocation of storage would required to copy keys (because moving const values is not possible, only copying).
For example you can see AssocVector
written by Andrei Alexandrescu: https://github.com/snaewe/loki-lib/blob/master/include/loki/AssocVector.h or small_unordered_flat_map
written by myself: https://github.com/slavenf/sfl-library/blob/master/include/sfl/small_unordered_flat_map.hpp
Both containers store key-value elements as std::pair<Key, T>
(keys are non-const).
As @slavenf says, this is to be able to rearange objects, that's one case where unordered_flat_map differs from std::unordered_map
. If you need const keys use unordered_node_map
.
When iterating over
robin_hood::unordered_map
using C++17's structured bindings the keys are not markedconst
as expected. This can lead to incorrect programs when keys are modified without updating of hash map internal structure.As an illustration let's see the program below. In the line
24
incorrect assignment is allowed which leads to the error in the internal structure of the hash map. Whenstd::unordered_map
is used (comment line14
and uncomment line15
) then in the line24
error is raised by the compiler (as expected) telling thatBoxed::value
is read-only object.Link to code in Compiler Explorer: https://gcc.godbolt.org/z/b9xqWxehn