Namespaces
Variants
Views
Actions

std::hash<std::unique_ptr>

From cppreference.com
< cpp‎ | memory‎ | unique ptr
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++23)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)
 
Dynamic memory management
Smart pointers
(C++11)
(C++11)
(C++11)
(until C++17)
(C++11)
(C++23)
Allocators
Memory resources
Uninitialized storage
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
Miscellaneous
(C++20)
(C++11)
(C++11)
 
 
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.

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<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(int nr) { std::cout << "Foo(" << nr << ")\n"; }
    ~Foo() { std::cout << "~Foo()\n"; }
    bool operator==(const Foo &other) { return nr == other.nr; };
    int nr;
};
 
int main()
{
    std::cout << std::boolalpha;
    Foo* foo = new Foo(5);
    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';
    std::cout << "    *up==*foo: " << (*up == *foo) << '\n';
 
    std::unique_ptr<Foo> other = std::make_unique<Foo>(5);
    std::cout << "     hash(up): " << std::hash<std::unique_ptr<Foo>>()(up) << '\n';
    std::cout << "  hash(other): " << std::hash<std::unique_ptr<Foo>>()(other) << '\n';
    std::cout << "  *up==*other: " <<(*up == *other) << '\n';
}

Possible output:

Foo(5)
     hash(up): 7167008
    hash(foo): 7167008
    *up==*foo: true
Foo(5)
     hash(up): 7167008
  hash(other): 7171152
  *up==*other: true
~Foo()
~Foo()

[edit] See also

(C++11)
hash function object
(class template) [edit]