I have a set like this: set<weak_ptr<Node>, owner_less<weak_ptr<Node> > > setName;
It works fine. But I would like to change it to an unordered set. However, I get about six pages of errors when I do that. Any ideas how to do that?
After looking through all the pages of error messages I found to lines that might help.
/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type
/usr/include/c++/4.7/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::weak_ptr<Node>]’:
An unordered_set is implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized.
std::unordered_set is an STL container and its introduced in C++11. It provides a functionality of a Set i.e. it can contains the unique elements only. unordered_set stores the elements internally using a Hash Table.
std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
An Unordered Set can be sorted by copying its elements to a Vector and then using the sort() method of the STL.
The short and unfortunate answer is that while shared_ptr<>
can be used safely as a key in an unordered set or map, weak_ptr<>
cannot and must not. No amount of trickery can make it safe.
This is because weak_ptr
's interface does not expose access to the shared control object, which is the basis of comparing by owner_before()
when used in an ordered set or map.
While it may seem reasonable to lock the pointer and then hash the shared_ptr
, it is not. If the last shared_ptr
goes out of scope the hash value will change, which will result in undefined behaviour next time your set or map is iterated. This will most likely go un-noticed until your code is in production in front of customers where you get unexpected and inexplicable loss of functionality occasionally, but your unit tests will still pass flawlessly, giving you the false idea that your test coverage is good, your code is reliable and it is the users, hardware or network that's to blame.
So, in summary, if you're going to use weak_pt
r's to build your non-owning object caches (for which they are excellent) you need use a std::set<weak_ptr>
and suffer the miniscule performance hit (although in reality this will be dwarfed by the performance loss caused by the mutex
that protects the set).
If you really want to use a weak_ptr
as an unordered key you will have to write your own (hint: use the address of the shared control block as the basis for the hash function).
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