RecyclerRootPtr.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. namespace Memory
  7. {
  8. template <typename T>
  9. class RecyclerRootPtr
  10. {
  11. public:
  12. RecyclerRootPtr() : ptr(nullptr) {};
  13. ~RecyclerRootPtr() { Assert(ptr == nullptr); }
  14. void Root(T * ptr, Recycler * recycler) { Assert(this->ptr == nullptr); recycler->RootAddRef(ptr); this->ptr = ptr; }
  15. void Unroot(Recycler * recycler) { Assert(this->ptr != nullptr); recycler->RootRelease(this->ptr); this->ptr = nullptr; }
  16. T * operator->() const { Assert(ptr != nullptr); return ptr; }
  17. operator T*() const { return ptr; }
  18. RecyclerRootPtr(RecyclerRootPtr<T>&&);
  19. RecyclerRootPtr& operator=(RecyclerRootPtr<T> &&);
  20. protected:
  21. T * ptr;
  22. private:
  23. RecyclerRootPtr(const RecyclerRootPtr<T>& ptr); // Disable
  24. RecyclerRootPtr& operator=(RecyclerRootPtr<T> const& ptr); // Disable
  25. };
  26. typedef RecyclerRootPtr<void> RecyclerRootVar;
  27. template <typename T>
  28. class AutoRecyclerRootPtr : public RecyclerRootPtr<T>
  29. {
  30. public:
  31. AutoRecyclerRootPtr(T * ptr, Recycler * recycler) : recycler(recycler)
  32. {
  33. Root(ptr);
  34. }
  35. ~AutoRecyclerRootPtr()
  36. {
  37. Unroot();
  38. }
  39. void Root(T * ptr)
  40. {
  41. Unroot();
  42. __super::Root(ptr, recycler);
  43. }
  44. void Unroot()
  45. {
  46. if (this->ptr != nullptr)
  47. {
  48. __super::Unroot(recycler);
  49. }
  50. }
  51. Recycler * GetRecycler() const
  52. {
  53. return recycler;
  54. }
  55. private:
  56. Recycler * const recycler;
  57. };
  58. typedef AutoRecyclerRootPtr<void> AutoRecyclerRootVar;
  59. }