Best practice for local variable scope in C ++ callback

I have a C ++ callback function triggered by a mouse down event. (IDE - VS2010.)

With each call, I would like to increase the simplicity of the counter, which is local to the callback area. Simply put, what is the best practice way to do this?

Thanks in advance for any opinions or directives.

+8
c ++
source share
1 answer

Replace the callback function with a functor - they can save state. 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; } 

Pay attention to the use of shared_ptr inside the functor - this is because f has a local copy of the functor (pay attention to the pass-by-value), and you want this copy to share its int with the functor that you have access to. Also note that f must take its argument by value, since you want to support all the called objects, not just functors.

+13
source share

All Articles