Search code examples
c++unordered-set

c++ unordered_set with shared_ptr search for raw pointer


I have a unordered_set with shared_ptrs as a key. This works fine in 99%, but in same cases I need to search the set from inside the class and I would like to avoid inheriting enable_shared_from_this, just because of that.

Can/how I search a unordered_set of shared_ptr by raw pointer.


Solution

  • Hashing a shared_ptr hashes get() and comparing a shared_ptr compares get(), so let's just make a non-owning shared_ptr with the aliasing constructor:

    std::shared_ptr<T> key(std::shared_ptr<T>(),
                           this /* or whatever pointer you want to search for */);
    

    And search the unordered_set with that.

    Compared to using a null deleter, this is cheaper as it doesn't allocate a control block.