std::hash <std::unique_ptr>

< cpp‎ | memory‎ | unique ptr
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types

Elementary string conversions
Dynamic memory management
Smart pointers
(until C++17)
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
C Library
Low level memory management
template<class T, class Deleter> struct hash<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<typename std::unique_ptr<T,D>::pointer> is enabled, and is disabled otherwise.

(since C++17)

When enabled, (since C++17) for a given std::unique_ptr<T, D> p, this specialization ensures that std::hash<std::unique_ptr<T, D>>()(p) == std::hash<typename std::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.

[edit] Example

#include <iostream>
#include <memory>
#include <functional>
struct Foo {
    Foo() { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n\n"; }
int main()
    Foo* foo = new Foo();
    std::unique_ptr<Foo> up(foo);
    std::cout << "hash(up):  " << std::hash<std::unique_ptr<Foo>>()(up) << '\n';
    std::cout << "hash(foo): " << std::hash<Foo*>()(foo) << '\n';


hash(up):  3686401041
hash(foo): 3686401041

[edit] See also

hash function object
(class template) [edit]