Namespaces
Variants

std:: hash <std::unique_ptr>

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (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)
(C++11) (until C++23)
template < class T, class Deleter >
struct hash < std:: unique_ptr < T, Deleter >> ;
(depuis C++11)

La spécialisation de modèle de std::hash pour std:: unique_ptr < T, Deleter > permet aux utilisateurs d'obtenir des hachages d'objets de type std:: unique_ptr < T, Deleter > .

La spécialisation std:: hash < std:: unique_ptr < T,D >> est activée (voir std::hash ) si std:: hash < typename std:: unique_ptr < T,D > :: pointer > est activée, et est désactivée sinon.

Lorsqu'il est activé, pour un std:: unique_ptr < T, D > p donné, cette spécialisation garantit que std:: hash < std:: unique_ptr < T, D >> ( ) ( p ) == std:: hash < typename std:: unique_ptr < T, D > :: pointer > ( ) ( p. get ( ) ) .

Les fonctions membres de cette spécialisation ne sont pas garanties d'être noexcept car le pointeur peut être un pointeur sophistiqué et son hachage pourrait lever une exception.

Exemple

#include <functional>
#include <iostream>
#include <memory>
struct Foo
{
    Foo(int num) : nr(num) { std::cout << "Foo(" << nr << ")\n"; }
    ~Foo() { std::cout << "~Foo()\n"; }
    bool operator==(const Foo &other) const { return nr == other.nr; };
    int nr;
};
int main()
{
    std::cout << std::boolalpha << std::hex;
    Foo* foo = new Foo(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";
}

Sortie possible :

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

Voir aussi

(C++11)
objet fonction de hachage
(modèle de classe)