I have a vector:
std::vector<uint16_t> free_ids;
I need for it operator== of my class GameObject. When an object is created, it will receive free id from vector, thus it will be "moved" from it to object. It will get values simply like this:
void init(void)
{
for(uint64_t i=0; i<30; ++i)
free_ids.push_back(i);
}
So I have class that uses that succesfully.
class GameObject
{
public:
static std::vector<GameObject*> created_objects; // all objects created ever
static constexpr auto& CO = created_objects;
GameObject()
{
id = free_ids.front(); // get id from vector
free_ids.erase(free_ids.begin()); // delete it from vector
CO.push_back(this); // add address to all object created ever
}
GameObject(const GameObject& other)
{
// copy attributes I didn't include in this code
id = free_ids.front();
free_ids.erase(free_ids.begin());
CO.push_back(this);
}
~GameObject()
{
free_ids.push_back(id); // return id to vector
CO.erase(std::remove(CO.begin(), CO.end(), this), CO.end());
// remove object by address
}
bool operator==(const GameObject& other)
{
return id==other.id; // check if id is the same (if it's the same object)
}
const uint64_t& get_id(void) const
{
return id;
}
private:
uint64_t id;
};
std::vector<GameObject*> GameObject::created_objects;
I'd love to have global constant of type GameObject
, but it will cause segmentation fault, because init()
was never called before main()
call
//const GameObject Progenitor; //segmentation fault, free_ids not initialized yet
And a sample program:
int main()
{
srand(time(NULL));
init();
const GameObject Progenitor; // It's temporary replacement for my global
std::vector<GameObject> clone_army;
clone_army.reserve(20); // GameObjects can't be reallocated bacause
// their addresses are stored in class static vector
auto& CA = clone_army;
for(uint64_t i=0; i<20; ++i)
CA.push_back(Progenitor);
std::cout << "Storage used. Unoccupied ids: " << std::endl;
for(auto& x : free_ids)
std::cout << x << std::endl;
auto& victim = clone_army[rand()%20]; // it's much more compilated
std::cout << "\nOne will die. Victim is... clone no. " << victim.get_id() << std::endl;
CA.erase(std::remove(CA.begin(), CA.end(), victim), CA.end());
// need to remove victim by value, operator== involved
std::cout << "\nProgenitor id: ";
for(auto& x : GameObject::CO)
std::cout << x->get_id() << std::endl;
}
Responsible headers:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
My question is, how to initialize std::vector<uint16_t> free_ids;
- which can't be const
, before any object of GameObject
class is ever created?
(There will be many progenitors of different inherited classes, template-like objects that I will use (already am but want to rearrange code) to create real-time clones)