I’m a beginner programmer, and I was wondering…
I need a unique ID for my object in a game
so I thought I define a global class that holds the global id, and when I call the constructor of an object it will be incremented, while calling the destructor of that object it decrements it.
Is it true that for every constructor call there will be a corresponding destructor?
class id_holder{
private:
int id_count;
public:
id_holder() {id_count = 0 ; std::cout<< "unique_id: I'm constructed"<<std::endl;}
~id_holder(){std::cout<<"unique_id: I'm destructed"<<std::endl;}
void increment_id(){id_count ++;};
void decrement_id(){id_count --;};
int get_id() {return id_count;};
};
class BaseObject {
protected:
void increment_id();
void decrement_id();
public:
virtual ~BaseObject(){decrement_id();}
BaseObject();
BaseObject(V2 pos, ObjectType idobj, double s, Color col);
};
BaseObject::BaseObject(){
//stuff
increment_id();
unique_id = bObj_id_counter.get_id();
}
BaseObject::BaseObject(V2 pos, ObjectType idobj, double s, Color col){
//stuff
increment_id();
unique_id = bObj_id_counter.get_id();
}
void BaseObject::increment_id(){
bObj_id_counter.increment_id();
}
void BaseObject::decrement_id(){
bObj_id_counter.decrement_id();
}
side question… is it possible to compare the memory adresses (this should be a unique id enough) of the objects instead of using an id_holder?
This is typically called “reference counting” and it has a wide range of uses. Yes it is possible to do, but yours won’t quite work correctly just yet.
idheld statically, and then use the curiously recurring template pattern to ensure that thisidis global only for specific types. Then each type gets a copy of the globalidduring construction.increment_id()anddecrement_id()are called by theid_holderclass, there is no reason to call them again in yourBaseObjectconstructor/destructor.This is a relatively elegant solution that allows for you to do things like constant-time lookups for an item given its ID. For example:
Warning pseudo-code (not compiled or tested)
Now you could hold a lookup table of
counted_objectsstored in a vector for very quick lookups: