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 >> ;
(seit C++11)

Die Template-Spezialisierung von std::hash für std:: unique_ptr < T, Deleter > ermöglicht es Benutzern, Hashwerte von Objekten des Typs std:: unique_ptr < T, Deleter > zu erhalten.

Die Spezialisierung std:: hash < std:: unique_ptr < T,D >> ist aktiviert (siehe std::hash ), falls std:: hash < typename std:: unique_ptr < T,D > :: pointer > aktiviert ist, und andernfalls deaktiviert.

Wenn aktiviert, stellt diese Spezialisierung für einen gegebenen std:: unique_ptr < T, D > p sicher, dass std:: hash < std:: unique_ptr < T, D >> ( ) ( p ) == std:: hash < typename std:: unique_ptr < T, D > :: pointer > ( ) ( p. get ( ) ) .

Die Memberfunktionen dieser Spezialisierung sind nicht garantiert noexcept, da der Zeiger ein Fancy Pointer sein könnte und dessen Hash eine Exception werfen könnte.

Beispiel

#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";
}

Mögliche Ausgabe:

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

Siehe auch

(C++11)
Hash-Funktionsobjekt
(Klassentemplate)