Pregunta

I'd written an event handler mechanism that works quite well. So I extended it to be more generalised and wrote an event handler to give me the keyboard state:

class KeybdHandler : public EventHandler<KeybdHandler>
{
private:
    Keyboard    _keybd;

public:
    void SetEvent( const Keyboard::KeyEvent & evt )
    {
        Keyboard::KeyEvent e = evt;

        // event holds the new keystate
        Notify(&e);

        // keystate is saved to keyboard
        _keybd.SetKey(e._Key, e._bKeyDown);
    }

    Keyboard & GetKeybd() { return _keybd; }
};

static KeybdHandler g_evtKeybd;

The KeybdHandler::Keyboard variable holds an array that denotes the keyboard state (e.g. one entry per key and bool variable denoting keydown or keyup).

So I create a static instance of this KeybdHandler class.

But when I call g_evtKeybd.GetKeybd(), the keyboard state is always empty / blank / all in keyup state.

When I make the KeybdHandler::Keyboard variable static, GetKeybd() returns a Keyboard object with state saved.

Why must the Keyboard variable be static if the containing object is static?

EDIT: Just want to clarify that SetEvent is always called through the static variable:

g_evtKeybd.SetEvent( Keyboard::KeyEvent((int)key, true));

EDIT2: I'm not certain if it's relevant. The KeybdHandler class is in a static library and linked to from another executable.

¿Fue útil?

Solución

You declared g_evtKeybd as a global static variable. In this context static has a different meaning. Each compilation unit will have it's own instance of g_evtKeybd which is probably not what you intended. As static members are shared by all instances of a class, all of them will return the same, even though you have multiple instances (hiding your actual mistake).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top