I have a class managed by std::shared_ptr
. This class has a hash and all the ==
, <
, etc. operators. For simplicity let's say that class is int
. What I want is a registry of all int
's currently in use that won't keep them alive longer than necessary, and has fast (faster than linear) lookup. This will be used to ensure I don't create two different int
objects of the same number, e.g. before I create a new 42
I'll check if a 42
already exists in the registry. It seems that I want something like Java's WeakHashMap
?
One possible solution is to use a std::unordered_set<std::shared_ptr<int>>
, and periodically iterate through the set and delete any elements that have a shared_ptr::use_count()
of 1. This is workable but not ideal since the objects stay alive longer than they need to.
Or I could use a std::vector<std::weak_ptr<int>>
, which would free immediately, but would require iterating through the whole vector every time I want to see if a specific int
already exists (slow).
A std::unordered_set<std::weak_ptr<int>>
would satisfy both my requirements, except for the fact that the hashes would have to change once the weak_ptr
expires, and "Container elements may not be modified since modification could change an element's hash and corrupt the container"
.
Is there a container with fast lookup that can handle changing hashes? Keep in mind it doesn't need to find the elements that changed, it just needs to not be corrupted by them.