std:: hash <std::unique_ptr>
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Modifiers | ||||
| Observers | ||||
| Non-member functions | ||||
|
(C++14)
(C++20)
|
||||
|
(until C++20)
(C++20)
|
||||
|
(C++20)
|
||||
| Helper classes | ||||
|
hash
<std::unique_ptr>
|
|
template
<
class
T,
class
Deleter
>
struct hash < std:: unique_ptr < T, Deleter >> ; |
(自 C++11 起) | |
针对 std:: unique_ptr < T, Deleter > 的 std::hash 模板特化允许用户获取 std:: unique_ptr < T, Deleter > 类型对象的哈希值。
当 std:: hash < typename std:: unique_ptr < T,D > :: pointer > 启用时(参见 std::hash ),特化模板 std:: hash < std:: unique_ptr < T,D >> 将同时启用,否则该特化将被禁用。
当启用时,对于给定的 std:: unique_ptr < T, D > p ,该特化确保 std:: hash < std:: unique_ptr < T, D >> ( ) ( p ) == std:: hash < typename std:: unique_ptr < T, D > :: pointer > ( ) ( p. get ( ) ) 。
此特化的成员函数不保证为 noexcept,因为指针可能是花式指针且其哈希操作可能抛出异常。
示例
#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"; }
可能的输出:
Foo(5) hash(up): acac20 hash(foo): acac20 *up==*foo: true Foo(5) hash(up): acac20 hash(other): acbc50 *up==*other: true ~Foo() ~Foo()
参见
|
(C++11)
|
哈希函数对象
(类模板) |