object_counter.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #pragma once
  2. #include <cstddef>
  3. #include <atomic>
  4. /**
  5. * Simple thread-safe per-class counter that can be used to make sure you don't
  6. * have any leaks in your code, or for statistical purposes.
  7. *
  8. * Example usage:
  9. * \code
  10. * class TMyClass: public TObjectCounter<TMyClass> {
  11. * // ...
  12. * };
  13. *
  14. * // In your code:
  15. * Cerr << "TMyClass instances in use: " << TMyClass::ObjectCount() << Endl;
  16. * \endcode
  17. */
  18. template <class T>
  19. class TObjectCounter {
  20. public:
  21. inline TObjectCounter() noexcept {
  22. ++Count_;
  23. }
  24. inline TObjectCounter(const TObjectCounter& /*item*/) noexcept {
  25. ++Count_;
  26. }
  27. inline ~TObjectCounter() {
  28. --Count_;
  29. }
  30. static inline long ObjectCount() noexcept {
  31. return Count_.load();
  32. }
  33. /**
  34. * Resets object count. Mainly for tests, as you don't want to do this in
  35. * your code and then end up with negative counts.
  36. *
  37. * \returns Current object count.
  38. */
  39. static inline long ResetObjectCount() noexcept {
  40. return Count_.exchange(0);
  41. }
  42. private:
  43. static std::atomic<intptr_t> Count_;
  44. };
  45. template <class T>
  46. std::atomic<intptr_t> TObjectCounter<T>::Count_ = 0;