std::hash<std::unique_ptr>
From cppreference.com
< cpp | memory | unique ptr
| 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<std::unique_ptr<T,D>> は、std::hash<typename std::unique_ptr<T,D>::pointer> が有効な場合に有効になり(std::hash を参照)、それ以外の場合は無効になります。
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) |
ハッシュ関数オブジェクト (クラステンプレート) |