ObjectPtr.h 1.0 KB

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