I'm currently working on a game in c++. since there's no garbage collector one has always to carefully delete the objects and also make sure that such objects are not accessed anymore once they got deleted.
Now as a project grows some objects may get referenced from more and more places. For example my units in the game may get referenced from the renderer, from the scene hierarchy, from the selection mechanism, from the HUD and so on. now - if a object gets deleted one has to make sure that all other classes that reference this object will be notified about it.
Or let's say it the other way arround - if i create a new class that may reference one of my units, i'll also have to change the code of the unit (or of the unit manager or whatever module delets the unit if it gets destroyed) to make sure this new module knows when the particular unit it currently references gets deleted.
Now I thoght there could be a simple event driven general purpose aproach to solve this problem by creating a baseclass to which one another object can subscribe. Something like this:
class DeletableBase;//forward declaration
class ISubscriber{
public:
virtual someObjectGotDeleted(DeletableBase* deletedObject)=0;
};
class DeletableBase{
private:
vector<ISubscriber*> subscribers;
public:
virtual ~DeletableBase(){
for(int i=0; i<subscribers.size(); i++)
subscribers[i]->someObjectGotDeleted(this);
}
subscribeForDeleteEvent(ISubscriber* subscriber){
subscribers.push_back(subscriber);
}
};
with that - if i reference any object that inherits from this class from a new class i can simply add myself as a subscriber and if the object will be deleted from any other place I will get notifed about it.
is this a "clean" way of coding?
ISubscriber
and moving it's functionality to DeletableBase instead - and upon subscription there will automatically a cross-subscription be established. the only catch is that each implementation ofsmeObjectGotDeleted
will have to call the base implementation – Unctuous