views:

175

answers:

1

Hi! I'm making a game engine in C++. It is supposed to read all its game-level logic from XML files, so I'm in need of a simple, but rock solid way of creating and handling events. So far all i have done is to use an Action class. It's practically equivalent to throwing callbacks around.

An example could be an object (a map), that can change the scene if you click it. What bothers me is that I want to be able to delete the scene without worrying about all the objects that used to activate it.

Is there a widely accepted way to do this? The way that I have done this so far is to make all the dependent/dependable objects inherit a dependent/dependable class. The class provides them with a list over objects that depend on them or that they depend on.

class Dependent
{
    protected:
        Dependent();
        /// Warning all connected \ref Dependent that the Dependent does not exist.
        ~Dependent();
        /// Connected Dependent \see connect(Dependent*, Dependent*)
        std::list<Dependent*>* dependents;
        /// Register a Dependent.
        void newDependent(Dependent*);
        /// Check if dependent on the given Dependent.
        bool listeningTo(const Dependent*) const;
        /// Used by a destructing connected Dependent to warn that it no longer exists.
        void stopListening(Dependent*);

    friend void connect(Dependent*, Dependent*);
};

All this for just the ability to check if an element has ceased to exist. There is no automatic checking that the objects don't call the other after one has been deleted, but I'm able to do the check without worrying about using pointer that lead to nowhere.

I'm hoping that there is a more elegant way to do this.

+2  A: 

It sounds like you want to use a signal library, such as boost::signals or sigc.

Either of those libraries will allow any of your objects to know when an event such as a click happens.

They can also automate the cleanup when either the signaling object or a listening object is destroyed.

Good luck!

Shmoopty
It's not the first time I consider using boost, so I guess it's time to give it a try. Hopefully it will help me make my code more elegant.
Styggentorsken