Maybe something like this will do:
class xyz {
public:
static xyz *create(){ return new xyz(); };
~xyz(){ int ind = xyz::_instances.indexOf(this); xyz::_instances[ind]=0; }
void doSomething(uint ind){
if(xyz::_instances.size()<=ind || xyz::_instances.value(ind)==0)
return;
xyz::_instances[ind]->inc();
}
private:
xyz(){ xyz::_instances << this; ref = 0; };
static QList<xyz*> _instances;
void inc(){ ref++; }
int ref;
};
class xyz {
public:
static xyz *create(){ return new xyz(); };
~xyz(){ int ind = xyz::_instances.indexOf(this); xyz::_instances[ind]=0; }
void doSomething(uint ind){
if(xyz::_instances.size()<=ind || xyz::_instances.value(ind)==0)
return;
xyz::_instances[ind]->inc();
}
private:
xyz(){ xyz::_instances << this; ref = 0; };
static QList<xyz*> _instances;
void inc(){ ref++; }
int ref;
};
To copy to clipboard, switch view to plain text mode
This makes sure you can't create an object on stack and stores all instances of the class in the class itself.
Edit: In the destructor the pointer in the list should be zeroed and a check for null pointer should be made before dereferencing it. I'll adjust the code...
Bookmarks