std::hash <std::unique_ptr>

template<class T, class Deleter> struct hash<unique_ptr<T, Deleter>>;
(C++11 起)

std::hashstd::unique_ptr<T, Deleter> 的模板特化允许用户获得 std::unique_ptr<T, Deleter> 类型对象的哈希值。

若启用 std::hash<typename std::unique_ptr<T,D>::pointer> ,则启用特化 std::hash<std::unique_ptr<T,D>> (见 std::hash ),否则禁用它。

(C++17 起)

启用时, (C++17 起)对于给定的 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 <iostream>
#include <memory>
#include <functional>
 
struct Foo {
    Foo() { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n\n"; }
};
 
int main()
{
    Foo* foo = new Foo();
    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';
}

输出:

Foo...
hash(up):  3686401041
hash(foo): 3686401041
~Foo...

参阅

(C++11)
哈希函数对象
(类模板)

版本历史

  • (当前 | 先前 2017年9月2日 (六) 10:58Fruderica讨论 | 贡献. . (1,518字节) (-168). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:58P12bot讨论 | 贡献 . . (1,686字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:07P12bot讨论 | 贡献 . . (1,686字节) (-61). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:20P12bot讨论 | 贡献 . . (1,747字节) (+273). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 03:41P12讨论 | 贡献 . . (1,474字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,474字节) (-19). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:55P12讨论 | 贡献 . . (1,493字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,493字节) (+1,493). . (Translated from the English version using Google Translate)