Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::hash<std::unique_ptr>

      From cppreference.com
      <cpp‎ |memory‎ |unique ptr
       
       
      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*)
      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>>;
      (since C++11)

      The template specialization ofstd::hash forstd::unique_ptr<T, Deleter> allows users to obtain hashes of objects of typestd::unique_ptr<T, Deleter>.

      The specializationstd::hash<std::unique_ptr<T,D>> is enabled (seestd::hash) ifstd::hash<typenamestd::unique_ptr<T,D>::pointer> is enabled, and is disabled otherwise.

      When enabled, for a givenstd::unique_ptr<T, D> p, this specialization ensures thatstd::hash<std::unique_ptr<T, D>>()(p)==std::hash<typenamestd::unique_ptr<T, D>::pointer>()(p.get()).

      The member functions of this specialization are not guaranteed to be noexcept because the pointer may be a fancy pointer and its hash might throw.

      [edit]Example

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

      Possible output:

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

      [edit]See also

      (C++11)
      hash function object
      (class template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/memory/unique_ptr/hash&oldid=167394"

      [8]ページ先頭

      ©2009-2025 Movatter.jp