I'm using external networking library which returns some magic structures representing opened sockets and the docs say that when inserting them into STL containers, they should be compared using std::owner_less
.
std::map<MagicStructure, std::shared_ptr<Client>, std::owner_less<MagicStructure>> sockets;
However I'd like to use unordered_map
instead. How can I do it? std::owner_less
is a comparator and it's useless for a hash map. Digging in the source code, MagicStructure
appears to be a typedef for std::shared_ptr
.
Unfortunately, it seems that you have to use a map
, and can't use unordered_map
for such scenario: http://wg21.cmeerw.net/lwg/issue1406
Hash support for the ownership-based equivalence relation cannot be provided by any user-defined manner because information about ownership sharing is not available to users at all. Therefore, the only way to provide ownership-based hash support is to offer it intrusively by the standard library.
In the other words, there is stored (returned by get()
) and owned pointer (which is deleted when reference count reaches 0) in a shared_ptr
: http://www.cplusplus.com/reference/memory/shared_ptr/get/ . For using owned pointer in an unordered_map
, you need owned pointer based hash()
and equals()
operations. But they are not provided in STL. And you can't implement them yourself (without reimplementing shared_ptr
and changing the definition of your MagicStructure
) because the owned pointer is not exposed by shared_ptr
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With