So I'm attempting to make a system where I have these resource manager classes and I came across a serious flaw with my set up. When I add a new object using my add function it returns a pointer. Do this again and the previous pointer is now garbage. I now know this is happening because adding (or even if I was trying to remove an object) will cause allocations / shifting cause the pointers to get desynced.
So my question is what is the proper way to make resource manager class? Should I just use a vector of pointers and create a new object every time I need to add?
Obj* addObj() {
Obj* test = new Obj;
test->val = count;
++count;
objects.push_back(test); //objects is a std::vector<Obj*> in this case. Instead of std::vector<Obj>
return objects.back();
}
Just in case my set up basically looks like this:
//My resouce
class Obj
{
public:
Obj() {
val = 0;
}
~Obj() {}
int val;
};
//Resouce manager
class ObjManager
{
public:
ObjManager() {
count = 0;
}
~ObjManager() {
}
Obj* addObj() {
Obj test;
test.val = count;
++count;
objects.push_back(test);
return &objects.back();
}
int count;
std::vector<Obj> objects;
};
int main()
{
ObjManager test;
Obj* obj = test.addObj(); //Add a new Object. Pointer is ok
test.addObj(); // Add another object. The pointer saved to obj is now garbage
std::cout << "Complete!" << std::endl;
}
↧