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.

80 lines
2.2 KiB

  1. #pragma once
  2. namespace CertSrv
  3. {
  4. typedef VOID (WINAPI* PFNAUTOCLEANUP)(VOID*);
  5. template<class PTR, PFNAUTOCLEANUP pfn, UINT_PTR pInvalid = NULL>
  6. class CAutoPtr {
  7. public:
  8. CAutoPtr() { m_ptr = pInvalid; }
  9. CAutoPtr(PTR ptr) : m_ptr(ptr) { }
  10. ~CAutoPtr() { Cleanup(); }
  11. bool IsValid() const { return(m_ptr != pInvalid); }
  12. bool IsInvalid()const { return(!IsValid()); }
  13. PTR operator=(PTR ptr) { return Attach(ptr); }
  14. operator PTR() const { return m_ptr; }
  15. PTR* operator &() { CSASSERT(NULL==m_ptr); return &m_ptr; }
  16. PTR& operator *() const { CSASSERT(NULL!=m_ptr); return *m_ptr; }
  17. PTR operator ->() const { return m_ptr; }
  18. bool operator ==(const PTR ptr) const { return m_ptr==ptr; }
  19. bool operator !=(const PTR ptr) const { return m_ptr!=ptr; }
  20. bool operator !() const { return NULL == m_ptr; }
  21. void Cleanup()
  22. {
  23. if (IsValid())
  24. {
  25. pfn(m_ptr);
  26. m_ptr = pInvalid;
  27. }
  28. }
  29. PTR Attach(PTR ptr)
  30. {
  31. Cleanup();
  32. m_ptr = ptr;
  33. return(*this);
  34. }
  35. PTR Detach()
  36. {
  37. PTR ptrTemp = m_ptr;
  38. m_ptr = pInvalid;
  39. return m_ptr;
  40. }
  41. private:
  42. // disable default copy constructor and assignment operator for
  43. // CAutoPtr objects
  44. CAutoPtr(const CAutoPtr& src) { }
  45. CAutoPtr operator=(CAutoPtr p) { }
  46. PTR m_ptr; // The member representing the object
  47. };
  48. #define DefineAutoClass(className, tData, pfnCleanup) \
  49. typedef CAutoPtr<tData, (PFNAUTOCLEANUP) pfnCleanup> className;
  50. #define DefineAutoClassEx(className, tData, pfnCleanup, pInvalid) \
  51. typedef CAutoPtr<tData, (PFNAUTOCLEANUP) pfnCleanup, \
  52. pInvalid> className;
  53. // Instances of the template C++ class for common data PTRs.
  54. DefineAutoClass(CAutoLPWSTR, LPWSTR, LocalFree);
  55. DefineAutoClass(CAutoLPSTR, LPSTR, LocalFree);
  56. DefineAutoClass(CAutoPBYTE, PBYTE, LocalFree);
  57. DefineAutoClass(CAutoHANDLE, HANDLE, CloseHandle);
  58. DefineAutoClass(CAutoBSTR, BSTR, SysFreeString);
  59. DefineAutoClass(CAutoHCERTTYPE, HCERTTYPE, CACloseCertType);
  60. DefineAutoClass(CAutoHKEY, HKEY, RegCloseKey);
  61. }; // namespace CertSrv