Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 260
Kevin Cain Avatar asked May 12 '12 17:05

Kevin Cain


People also ask

Can callback function access global variable?

This means the callback is a closure . Closures have access to the containing function's scope, so the callback function can access the containing functions' variables, and even the variables from the global scope.

Can a local variable be used outside its scope?

Local Variables Variables defined within a function or block are said to be local to those functions. Anything between '{' and '}' is said to inside a block. Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.

What happens to a local variable when it goes out of scope?

These variables are referred to as local because they exist (and are visible) only during the lifetime of the method. They are said to have local scope. When the method ends, the variable goes out of scope and is destroyed. C# divides the world of types into value types and reference types.


1 Answers

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.

like image 195
Stuart Golodetz Avatar answered Oct 17 '22 01:10

Stuart Golodetz