gc.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef AFUN_GC_HPP
  2. #define AFUN_GC_HPP
  3. #include "tool.hpp"
  4. #include "aFunCoreExport.h"
  5. #include "queue"
  6. namespace aFuncore {
  7. typedef unsigned GcCount;
  8. AFUN_CORE_EXPORT class GcObjectBase {
  9. bool not_clear; // 不清除
  10. bool reachable; // 可达标记 [同时标识已迭代]
  11. GcCount reference; // 引用计数
  12. protected:
  13. GcObjectBase() : not_clear{false}, reference{0}, reachable{false} {}
  14. virtual ~GcObjectBase()=default;
  15. GcObjectBase(const GcObjectBase &)=delete;
  16. GcObjectBase &operator=(const GcObjectBase &)=delete;
  17. public:
  18. void addReference() {reference++;}
  19. void delReference() {reference--;}
  20. void setClear(bool clear=false) {not_clear=!clear;}
  21. void setReachable(bool is_reference=false) {reachable=is_reference;}
  22. };
  23. template <class T>
  24. class GcObject : public GcObjectBase {
  25. T *prev;
  26. T *next;
  27. protected:
  28. GcObject() : GcObjectBase(), prev {nullptr}, next {nullptr} {}
  29. public:
  30. void addObject(T *&chain) {
  31. if (chain != nullptr) {
  32. next = chain;
  33. chain->prev = dynamic_cast<T *>(this);
  34. }
  35. chain = dynamic_cast<T *>(this);
  36. }
  37. void delObject(T *&chain) {
  38. if (next != nullptr)
  39. next->prev = prev;
  40. if (prev == nullptr)
  41. chain = next;
  42. else
  43. prev->next = next;
  44. }
  45. static void destruct(T *&chain) {
  46. for (T *tmp = chain, *n; tmp != nullptr; tmp = n) {
  47. n = tmp->next;
  48. delete tmp;
  49. }
  50. }
  51. };
  52. AFUN_CORE_EXPORT class GcList {
  53. std::queue<GcObjectBase *> queue;
  54. public :
  55. size_t add(GcObjectBase *obj);
  56. GcObjectBase *pop();
  57. [[nodiscard]] size_t getSize() const {return queue.size();}
  58. [[nodiscard]] size_t isEmpty() const {return queue.empty();}
  59. };
  60. };
  61. #endif //AFUN_GC_HPP