ObjectPtr.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #pragma once
  2. #include <AK/StdLibExtras.h>
  3. // This is a stopgap pointer. It's not meant to stick around forever.
  4. template<typename T>
  5. class ObjectPtr {
  6. public:
  7. ObjectPtr() {}
  8. ObjectPtr(T* ptr)
  9. : m_ptr(ptr)
  10. {
  11. }
  12. ObjectPtr(T& ptr)
  13. : m_ptr(&ptr)
  14. {
  15. }
  16. ~ObjectPtr()
  17. {
  18. clear();
  19. }
  20. void clear()
  21. {
  22. if (m_ptr && !m_ptr->parent())
  23. delete m_ptr;
  24. m_ptr = nullptr;
  25. }
  26. ObjectPtr& operator=(std::nullptr_t)
  27. {
  28. clear();
  29. return *this;
  30. }
  31. template<typename U>
  32. ObjectPtr(U* ptr)
  33. : m_ptr(static_cast<T*>(ptr))
  34. {
  35. }
  36. ObjectPtr(const ObjectPtr& other)
  37. : m_ptr(other.m_ptr)
  38. {
  39. }
  40. template<typename U>
  41. ObjectPtr(const ObjectPtr<U>& other)
  42. : m_ptr(static_cast<T*>(const_cast<ObjectPtr<U>&>(other).ptr()))
  43. {
  44. }
  45. ObjectPtr(ObjectPtr&& other)
  46. {
  47. m_ptr = other.leak_ptr();
  48. }
  49. template<typename U>
  50. ObjectPtr(const ObjectPtr<U>&& other)
  51. {
  52. m_ptr = static_cast<T*>(const_cast<ObjectPtr<U>&>(other).leak_ptr());
  53. }
  54. ObjectPtr& operator=(const ObjectPtr& other)
  55. {
  56. if (this != &other) {
  57. clear();
  58. m_ptr = other.m_ptr;
  59. }
  60. return *this;
  61. }
  62. ObjectPtr& operator=(ObjectPtr&& other)
  63. {
  64. if (this != &other) {
  65. clear();
  66. m_ptr = exchange(other.m_ptr, nullptr);
  67. }
  68. return *this;
  69. }
  70. T* operator->() { return m_ptr; }
  71. const T* operator->() const { return m_ptr; }
  72. operator T*() { return m_ptr; }
  73. operator const T*() const { return m_ptr; }
  74. T& operator*() { return *m_ptr; }
  75. const T& operator*() const { return *m_ptr; }
  76. T* ptr() const { return m_ptr; }
  77. T* leak_ptr() { return exchange(m_ptr, nullptr); }
  78. operator bool() const { return !!m_ptr; }
  79. private:
  80. T* m_ptr { nullptr };
  81. };