ObjectPtr.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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) : m_ptr(ptr) {}
  9. ObjectPtr(T& ptr) : m_ptr(&ptr) {}
  10. ~ObjectPtr()
  11. {
  12. if (m_ptr && !m_ptr->parent())
  13. delete m_ptr;
  14. }
  15. ObjectPtr(const ObjectPtr& other)
  16. : m_ptr(other.m_ptr)
  17. {
  18. }
  19. ObjectPtr(ObjectPtr&& other)
  20. {
  21. m_ptr = exchange(other.m_ptr, nullptr);
  22. }
  23. ObjectPtr& operator=(const ObjectPtr& other)
  24. {
  25. m_ptr = other.m_ptr;
  26. return *this;
  27. }
  28. ObjectPtr& operator=(ObjectPtr&& other)
  29. {
  30. if (this != &other) {
  31. m_ptr = exchange(other.m_ptr, nullptr);
  32. }
  33. return *this;
  34. }
  35. T* operator->() { return m_ptr; }
  36. const T* operator->() const { return m_ptr; }
  37. operator T*() { return m_ptr; }
  38. operator const T*() const { return m_ptr; }
  39. T& operator*() { return *m_ptr; }
  40. const T& operator*() const { return *m_ptr; }
  41. private:
  42. T* m_ptr { nullptr };
  43. };