Leaked source code of windows server 2003
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.

134 lines
2.3 KiB

  1. ///////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright (c) 1998, Microsoft Corp. All rights reserved.
  4. //
  5. // FILE
  6. //
  7. // autohdl.h
  8. //
  9. // SYNOPSIS
  10. //
  11. // This file defines the class auto_handle.
  12. //
  13. // MODIFICATION HISTORY
  14. //
  15. // 01/27/1998 Original version.
  16. // 02/24/1998 Added the attach() method.
  17. // 11/17/1998 Make type safe.
  18. //
  19. ///////////////////////////////////////////////////////////////////////////////
  20. #ifndef _AUTOHANDLE_H_
  21. #define _AUTOHANDLE_H_
  22. #include <nocopy.h>
  23. // return type is not a UDT or reference to a UDT. Will produce errors if
  24. // applied using infix notation
  25. #pragma warning(disable:4284)
  26. ///////////////////////////////////////////////////////////////////////////////
  27. //
  28. // CLASS
  29. //
  30. // auto_handle<>
  31. //
  32. ///////////////////////////////////////////////////////////////////////////////
  33. template< class T = HANDLE,
  34. class PFn = BOOL (WINAPI*)(HANDLE),
  35. PFn CloseFn = &CloseHandle
  36. >
  37. class auto_handle : NonCopyable
  38. {
  39. public:
  40. typedef T element_type;
  41. explicit auto_handle(T t = T()) throw ()
  42. : handle(t)
  43. { }
  44. T& operator=(T t) throw ()
  45. {
  46. attach(t);
  47. return handle;
  48. }
  49. ~auto_handle() throw ()
  50. {
  51. _close();
  52. }
  53. T* operator&() throw ()
  54. {
  55. close();
  56. return &handle;
  57. }
  58. T operator->() const throw ()
  59. {
  60. return handle;
  61. }
  62. operator T() throw ()
  63. {
  64. return handle;
  65. }
  66. operator const T() const throw ()
  67. {
  68. return handle;
  69. }
  70. bool operator!() const throw ()
  71. {
  72. return handle == T();
  73. }
  74. operator bool() const throw()
  75. {
  76. return !operator!();
  77. }
  78. void attach(T t) throw ()
  79. {
  80. _close();
  81. handle = t;
  82. }
  83. void close() throw ()
  84. {
  85. if (handle != T())
  86. {
  87. CloseFn(handle);
  88. handle = T();
  89. }
  90. }
  91. T get() const throw ()
  92. {
  93. return handle;
  94. }
  95. T release() throw ()
  96. {
  97. T tmp = handle;
  98. handle = T();
  99. return tmp;
  100. }
  101. private:
  102. void _close() throw ()
  103. {
  104. if (handle != T()) { CloseFn(handle); }
  105. }
  106. T handle;
  107. };
  108. #endif // _AUTOHANDLE_H_