-
Pointers
I have a bit of a design problem. I need to have an array of objects, however this array gets resized and elements moved. I need a way to keep a reference to each element without knowing where it is and retrn said reference.
I was thinking of creating something like a templated class with an array of smart pointers and have a lookup table for the pointers and use that table to return the reference to the desired element or something along those lines...
Any ideas?
-
http://code-dynasty.net/articles/C_A...Programming/80
You're looking for either std::vector<> or std::list<>.
-
But how do I keep a reference to an object?
I am trying to create something to keep all of my objects of a type, or derived type, in one place. New objects get created and deleted all the time. Now a pointer to an object in a vector is fine, until the vector get resized, isn't it possible for the memory block to be moved somewhere different alltogether? This would mean that my initial pointer to the object would now be useless! I need to be able to have a pointer, or a UID I can use to keep track of these elements no matter where they are in the list or memory location!
-
Code:
std::vector<BaseClass*> myBase;
myBase.push_back(new ChildClass);
myBase.push_back(new ChildChildClass);
myBase.front()->DisplayMsg();
myBase[1]->DisplayMsg();
delete myBase[0];
delete myBase.begin() + 1;
myBase.remove(myBase.begin(), myBase.end());
This code is pointless but it's just to show you that you don't need to have your pointers outside of the vector, you can just pick them as you want.
-
I see where you coming from, fair enough.