ComPtr.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. /* Oh no I have my own com pointer class, the world is ending, how dare you
  18. * write your own! */
  19. template<typename T> class ComPtr {
  20. T *ptr;
  21. inline void Kill()
  22. {
  23. if (ptr)
  24. ptr->Release();
  25. }
  26. inline void Replace(T *p)
  27. {
  28. if (ptr != p) {
  29. if (p) p->AddRef();
  30. if (ptr) ptr->Release();
  31. ptr = p;
  32. }
  33. }
  34. public:
  35. inline ComPtr() : ptr(NULL) {}
  36. inline ComPtr(T *p) : ptr(p) {if (ptr) ptr->AddRef();}
  37. inline ComPtr(const ComPtr &c) : ptr(c.ptr) {if (ptr) ptr->AddRef();}
  38. inline ComPtr(ComPtr &&c) : ptr(c.ptr) {c.ptr = NULL;}
  39. inline ~ComPtr() {Kill();}
  40. inline void Clear()
  41. {
  42. if (ptr) {
  43. ptr->Release();
  44. ptr = NULL;
  45. }
  46. }
  47. inline ComPtr &operator=(T *p)
  48. {
  49. Replace(p);
  50. return *this;
  51. }
  52. inline ComPtr &operator=(const ComPtr &c)
  53. {
  54. Replace(c.ptr);
  55. return *this;
  56. }
  57. inline ComPtr &operator=(ComPtr &&c)
  58. {
  59. if (this != &c) {
  60. Kill();
  61. ptr = c.ptr;
  62. c.ptr = NULL;
  63. }
  64. return *this;
  65. }
  66. inline T **Assign() {Clear(); return &ptr;}
  67. inline void Set(T *p) {Kill(); ptr = p;}
  68. inline T *Get() const {return ptr;}
  69. /* nabbed this one from virtualdub */
  70. inline T **operator~() {return Assign();}
  71. inline operator T*() const {return ptr;}
  72. inline T *operator->() const {return ptr;}
  73. inline bool operator==(T *p) const {return ptr == p;}
  74. inline bool operator!=(T *p) const {return ptr != p;}
  75. inline bool operator!() const {return !ptr;}
  76. };