diff options
author | Devtools Arcadia <[email protected]> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <[email protected]> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /util/generic/object_counter.h |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'util/generic/object_counter.h')
-rw-r--r-- | util/generic/object_counter.h | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/util/generic/object_counter.h b/util/generic/object_counter.h new file mode 100644 index 00000000000..5257afa2e60 --- /dev/null +++ b/util/generic/object_counter.h @@ -0,0 +1,53 @@ +#pragma once + +#include <util/system/atomic.h> + +/** + * Simple thread-safe per-class counter that can be used to make sure you don't + * have any leaks in your code, or for statistical purposes. + * + * Example usage: + * \code + * class TMyClass: public TObjectCounter<TMyClass> { + * // ... + * }; + * + * // In your code: + * Cerr << "TMyClass instances in use: " << TMyClass::ObjectCount() << Endl; + * \endcode + */ +template <class T> +class TObjectCounter { +public: + inline TObjectCounter() noexcept { + AtomicIncrement(Count_); + } + + inline TObjectCounter(const TObjectCounter& /*item*/) noexcept { + AtomicIncrement(Count_); + } + + inline ~TObjectCounter() { + AtomicDecrement(Count_); + } + + static inline long ObjectCount() noexcept { + return AtomicGet(Count_); + } + + /** + * Resets object count. Mainly for tests, as you don't want to do this in + * your code and then end up with negative counts. + * + * \returns Current object count. + */ + static inline long ResetObjectCount() noexcept { + return AtomicSwap(&Count_, 0); + } + +private: + static TAtomic Count_; +}; + +template <class T> +TAtomic TObjectCounter<T>::Count_ = 0; |