std::hash<std::unique_ptr> - cppreference.com

From cppreference.com

template<classT,classDeleter>structhash<std::unique_ptr<T,Deleter>>;(since C++11)The template specialization of

std::hash

for std::unique_ptr<T,Deleter> allows users to obtain hashes of objects of type std::unique_ptr<T,Deleter>.

The specialization std::hash<std::unique_ptr<T,D>> is enabled (see

std::hash

) if std::hash<typenamestd::unique_ptr<T,D>::pointer> is enabled, and is disabled otherwise.

When enabled, for a given std::unique_ptr<T,D>p, this specialization ensures that std::hash<std::unique_ptr<T,D>>()(p)==std::hash<typenamestd::unique_ptr<T,D>::pointer>()(p.get()).

The member functions of this specialization are not guaranteed to be noexcept because the pointer may be a fancy pointer and its hash might throw.

Example

Run this code

#include<functional>#include<iostream>#include<memory>structFoo{Foo(intnum):nr(num){std::cout<<"Foo("<<nr<<")\n";}~Foo(){std::cout<<"~Foo()\n";}booloperator==(constFoo&other)const{returnnr==other.nr;};intnr;};intmain(){std::cout<<std::boolalpha<<std::hex;Foo*foo=newFoo(5);std::unique_ptr<Foo>up(foo);std::cout<<"hash(up): "<<std::hash<std::unique_ptr<Foo>>()(up)<<'\n'<<"hash(foo): "<<std::hash<Foo*>()(foo)<<'\n'<<"*up==*foo: "<<(*up==*foo)<<"\n\n";std::unique_ptr<Foo>other=std::make_unique<Foo>(5);std::cout<<"hash(up): "<<std::hash<std::unique_ptr<Foo>>()(up)<<'\n'<<"hash(other): "<<std::hash<std::unique_ptr<Foo>>()(other)<<'\n'<<"*up==*other: "<<(*up==*other)<<"\n\n";}Possible output:

Foo(5) hash(up): acac20 hash(foo): acac20 *up==*foo: true Foo(5) hash(up): acac20 hash(other): acbc50 *up==*other: true ~Foo() ~Foo() See also

(C++11)

hash function object
(class template)

[edit]