aboutsummaryrefslogtreecommitdiffstats
path: root/util/generic/object_counter.h
blob: 57617101eeae09e082a444551cb7457eb9c40c1e (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
54
#pragma once

#include <cstddef>
#include <atomic>

/**
 * 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 {
        ++Count_;
    }

    inline TObjectCounter(const TObjectCounter& /*item*/) noexcept {
        ++Count_;
    }

    inline ~TObjectCounter() {
        --Count_;
    }

    static inline long ObjectCount() noexcept {
        return Count_.load();
    }

    /**
     * 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 Count_.exchange(0);
    }

private:
    static std::atomic<intptr_t> Count_;
};

template <class T>
std::atomic<intptr_t> TObjectCounter<T>::Count_ = 0;