Ref.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #include "Base.h"
  2. #include "Ref.h"
  3. #include "Game.h"
  4. namespace gameplay
  5. {
  6. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  7. void* trackRef(Ref* ref);
  8. void untrackRef(Ref* ref, void* record);
  9. #endif
  10. Ref::Ref() :
  11. _refCount(1)
  12. {
  13. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  14. __record = trackRef(this);
  15. #endif
  16. }
  17. Ref::~Ref()
  18. {
  19. }
  20. void Ref::addRef()
  21. {
  22. ++_refCount;
  23. }
  24. void Ref::release()
  25. {
  26. if ((--_refCount) <= 0)
  27. {
  28. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  29. untrackRef(this, __record);
  30. #endif
  31. delete this;
  32. }
  33. }
  34. unsigned int Ref::getRefCount() const
  35. {
  36. return _refCount;
  37. }
  38. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  39. struct RefAllocationRecord
  40. {
  41. Ref* ref;
  42. RefAllocationRecord* next;
  43. RefAllocationRecord* prev;
  44. };
  45. RefAllocationRecord* __refAllocations = 0;
  46. int __refAllocationCount = 0;
  47. void Ref::printLeaks()
  48. {
  49. // Dump Ref object memory leaks
  50. if (__refAllocationCount == 0)
  51. {
  52. printError("[memory] All Ref objects successfully cleaned up (no leaks detected).");
  53. }
  54. else
  55. {
  56. printError("[memory] WARNING: %d Ref objects still active in memory.", __refAllocationCount);
  57. for (RefAllocationRecord* rec = __refAllocations; rec != NULL; rec = rec->next)
  58. {
  59. Ref* ref = rec->ref;
  60. const char* type = typeid(*ref).name();
  61. printError("[memory] LEAK: Ref object '%s' still active with reference count %d.", (type ? type : ""), ref->getRefCount());
  62. }
  63. }
  64. }
  65. void* trackRef(Ref* ref)
  66. {
  67. // Create memory allocation record
  68. RefAllocationRecord* rec = (RefAllocationRecord*)malloc(sizeof(RefAllocationRecord));
  69. rec->ref = ref;
  70. rec->next = __refAllocations;
  71. rec->prev = 0;
  72. if (__refAllocations)
  73. __refAllocations->prev = rec;
  74. __refAllocations = rec;
  75. ++__refAllocationCount;
  76. return rec;
  77. }
  78. void untrackRef(Ref* ref, void* record)
  79. {
  80. RefAllocationRecord* rec = (RefAllocationRecord*)record;
  81. if (rec->ref != ref)
  82. {
  83. printError("[memory] CORRUPTION: Attempting to free Ref with invalid ref tracking record.");
  84. return;
  85. }
  86. // Link this item out
  87. if (__refAllocations == rec)
  88. __refAllocations = rec->next;
  89. if (rec->prev)
  90. rec->prev->next = rec->next;
  91. if (rec->next)
  92. rec->next->prev = rec->prev;
  93. free((void*)rec);
  94. --__refAllocationCount;
  95. }
  96. #endif
  97. }