I want to use my function assign
below, to store a struct of unknown type at a specific memory address stored in a void pointer. This works fine for some structs (e.g. with Test1
), but for other structs it does not work (e.g. with Test2
). Unfortunately, I could not find any pattern for what sort of structs it will work, as it has worked for some POD and non-POD structs.
What criteria must be fulfilled for a struct in order to store it this way?
#include <vector>
template <typename T>
void assign(void* p, T obj){
T* t = reinterpret_cast<T*>(p);
*t = obj;
}
struct Test1{
int i1;
int i2;
};
struct Test2{
std::vector<int> i;
};
int main()
{
void* p = new char[100];
Test1 test1;
test1.i1 = 0;
test1.i2 = 0;
Test2 test2;
test2.i = std::vector<int>();
assign(p, test1);
assign(p, test2);
delete[] p;
return 0;
}
Edit:
Why do I want to have this? I am currently implementing a game engine that uses an entity-component-system model (An entity is a game object, a component is kind of its attribute(s) and a system implements the logic to modify components.). There is a class that stores and manages entities (not surprisingly called EntityManager
). Some programmer that uses my engine can define components (simply structs, only meant to contain data and no functionality) for an entity. The EntityManager
therefore needs to store objects whose type is not known beforehand. A further restriction is that the components should be stored in an efficient way, i.e. behind each other in memory. This is the reason why a simple approach like having a base class Component
and then having a member variable vector<vector<Component*>>
is not appropriate.
My solution is that the EntityManager
allocates enough space to store a certain user-defined maximal number of entities beforehand. A given component can then be stored with the assign
function above.