aboutsummaryrefslogtreecommitdiffstats
path: root/util/generic/object_counter.h
blob: 5257afa2e60e0df3706c57cf03dfca20dcc24b0b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;