Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 unordered_set with std::owner_less-like hashing

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.

like image 329
Sebastian Nowak Avatar asked Jul 13 '15 07:07

Sebastian Nowak


1 Answers

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 .

like image 68
Serge Rogatch Avatar answered Sep 21 '22 18:09

Serge Rogatch