命名空间
变体
操作

std::hash<std::unique_ptr>

来自 cppreference.cn
< cpp‎ | memory‎ | unique ptr
 
 
内存管理库
(仅为解释目的*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(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)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
template< class T, class Deleter >
struct hash<std::unique_ptr<T, Deleter>>;
(自 C++11 起)

std::hash 的 std::unique_ptr<T, Deleter> 模板特化允许用户获取 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)
哈希函数对象
(类模板) [编辑]