Megidd
Megidd

Reputation: 7979

Count number of all calls to a class function

I have a class like this:

class Handler : public QObject
{
    Q_OBJECT
public:
    explicit Handler(Scene *scene, QObject *parent = nullptr);
    ~Handler();
    void runTests(const QVector<Test> *tests);

private:
    Scene *m_scene; // parent, not owned
    const QVector<Test> *m_tests; // Not owned, set by others
};

The function runTests is:

void Handler::runTests(const QVector<Test> *tests)
{
    if (tests->isEmpty()) {
        return;
    }

    m_tests = tests;

    // ... do things ...

    return;
}

I intend to count the number of calls to runTests function by any object instantiated from Handler class. I'm confused how to use static members to do so. Can anybody help?

Upvotes: 0

Views: 174

Answers (1)

ChrisMM
ChrisMM

Reputation: 10105

If it shouldn't matter what Handler calls it, then static is the way to go. You can place the static member in the class, as a private variable, or just put it inside the function.

void Handler::runTests(const QVector<Test> *tests)
{
    static size_t _numTimesCalled = 0;
    ++_numTimesCalled;

    if (tests->isEmpty()) {
        return;
    }

    m_tests = tests;

    // ... do things ...

    return;
}

Upvotes: 1

Related Questions