ComPtr.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2013 Hugh Bailey <[email protected]>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #pragma once
  17. template<typename T> class ComPtr {
  18. T *ptr;
  19. inline void Kill()
  20. {
  21. if (ptr)
  22. ptr->Release();
  23. }
  24. inline void Replace(T *p)
  25. {
  26. if (ptr != p) {
  27. if (p) p->AddRef();
  28. if (ptr) ptr->Release();
  29. ptr = p;
  30. }
  31. }
  32. public:
  33. inline ComPtr() : ptr(NULL) {}
  34. inline ComPtr(T *p) : ptr(p) {if (ptr) ptr->AddRef();}
  35. inline ComPtr(const ComPtr &c) : ptr(c.ptr) {if (ptr) ptr->AddRef();}
  36. inline ComPtr(ComPtr &&c) : ptr(c.ptr) {c.ptr = NULL;}
  37. inline ~ComPtr() {Kill();}
  38. inline void Clear()
  39. {
  40. if (ptr) {
  41. ptr->Release();
  42. ptr = NULL;
  43. }
  44. }
  45. inline ComPtr &operator=(T *p)
  46. {
  47. Replace(p);
  48. return *this;
  49. }
  50. inline ComPtr &operator=(const ComPtr &c)
  51. {
  52. Replace(c.ptr);
  53. return *this;
  54. }
  55. inline ComPtr &operator=(ComPtr &&c)
  56. {
  57. if (this != &c) {
  58. Kill();
  59. ptr = c.ptr;
  60. c.ptr = NULL;
  61. }
  62. return *this;
  63. }
  64. inline T **Assign() {Clear(); return &ptr;}
  65. inline void Set(T *p) {Kill(); ptr = p;}
  66. inline T *Get() const {return ptr;}
  67. inline operator T*() const {return ptr;}
  68. inline T *operator->() const {return ptr;}
  69. inline bool operator==(T *p) const {return ptr == p;}
  70. inline bool operator!=(T *p) const {return ptr != p;}
  71. inline bool operator!() const {return !ptr;}
  72. };