Best practice for local variable scope in a C++ callback

c++

Solution

Replace your callback function with a functor - they can store state. An example functor:

#include <iostream>
#include <memory>

class Functor
{
private:
    std::shared_ptr<int> m_count;

public:
    Functor()
    :    m_count(new int(0))
    {}

    void operator()()
    {
        ++(*m_count);
        // do other stuff...
    }

    int count() const
    {
        return *m_count;
    }
};

template <typename F>
void f(F callback)
{
    // do stuff
    callback();
    // do other stuff
}

int main()
{
    Functor callback;
    f(callback);
    f(callback);
    std::cout << callback.count();    // prints 2
    return 0;
}

Note the use of a `shared_ptr` inside the functor - this is because `f` has a local copy of the functor (note the pass-by-value) and you want that copy to share its `int` with the functor to which you have access. Note also that `f` has to take its argument by value, since you want to support all callables, and not just functors.

Problem

I have a functioning C++ callback function, triggered by a user 'mouse down' event. (The IDE is VS2010.) With each call, I'd like to increment a simple count variable that is local to the callback's scope. Simply put, what is the 'best practices' way to do this? Thanks in advance for any opinions or directives.

Original source