Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.6 KiB

  1. //
  2. // auto_h.h
  3. //
  4. #pragma once
  5. template<class T> class auto_handle;
  6. template<class T>
  7. class CHandleProxy
  8. {
  9. public:
  10. CHandleProxy (auto_handle<T>& ah) :
  11. m_ah(ah) {};
  12. CHandleProxy (const auto_handle<T>& ah) :
  13. m_ah(const_cast<auto_handle<T>&> (ah)) {};
  14. operator T* () { return &m_ah.h; }
  15. operator const T* () const { return &m_ah.h; }
  16. operator auto_handle<T>* () { return &m_ah; }
  17. protected:
  18. mutable auto_handle<T>& m_ah;
  19. };
  20. template<class T>
  21. class auto_handle
  22. {
  23. public:
  24. auto_handle(T p = 0)
  25. : h(p) {};
  26. auto_handle(const auto_handle<T>& rhs)
  27. : h(rhs.release()) {};
  28. ~auto_handle()
  29. { if (h && INVALID_HANDLE_VALUE != h) CloseHandle(h); };
  30. auto_handle<T>& operator= (const auto_handle<T>& rhs)
  31. { if (this != rhs.getThis())
  32. reset (rhs.release() );
  33. return *this;
  34. };
  35. auto_handle<T>& operator= (HANDLE rhs)
  36. { if ((NULL == rhs) || (INVALID_HANDLE_VALUE == rhs))
  37. {
  38. AssertSz(false, "assigning invalid HANDLE to auto_handle- use .reset instead");
  39. // be sure and go through auto_os for dbg.lib
  40. //auto_os os;
  41. //os = (BOOL)FALSE;
  42. //AssertSz(FALSE, "auto_handle<T>::op= Shouldn't ever get here");
  43. }
  44. reset (rhs);
  45. return *this;
  46. };
  47. CHandleProxy<T> operator& ()
  48. { reset(); return CHandleProxy<T> (*this); }; // &h;
  49. const CHandleProxy<T> operator& () const
  50. { return CHandleProxy<T> (*this); }; // &h;
  51. operator T ()
  52. { return h; };
  53. // Checks for NULL
  54. bool operator! ()
  55. { return h == NULL; }
  56. operator bool()
  57. { return h != NULL; }
  58. bool operator== (LPVOID lpv) const
  59. { return h == lpv; };
  60. bool operator!= (LPVOID lpv) const
  61. { return h != lpv; };
  62. bool operator== (const auto_handle<T>& rhs) const
  63. { return h == rhs.h; };
  64. bool operator< (const auto_handle<T>& rhs) const
  65. { return h < rhs.h; };
  66. // return value of current dumb pointer
  67. T get() const
  68. { return h; };
  69. // relinquish ownership
  70. T release() const
  71. { T oldh = h;
  72. h = 0;
  73. return oldh;
  74. };
  75. // delete owned pointer; assume ownership of p
  76. BOOL reset (T p = 0)
  77. {
  78. BOOL rt = TRUE;
  79. if (h && INVALID_HANDLE_VALUE != h)
  80. rt = CloseHandle(h);
  81. h = p;
  82. return rt;
  83. };
  84. private:
  85. friend class CHandleProxy<T>;
  86. // operator& throws off operator=
  87. const auto_handle<T> * getThis() const
  88. { return this; };
  89. // mutable is needed for release call in ctor and copy ctor
  90. mutable T h;
  91. };