In trying to patch memory leaks among other things in a side project I’ve totally confused myself with pointers and lists and maps and memory, etc.
I want to create a list of objects to use throughout the programs life. But I also want to use a map to quickly access individual objects from that list through their unique id. I figured I could have a map of pointers to the objects in the list to cut down on memory size.
Is this possible?
I’ve been working on test code that looks like:
list<cObject> mylist;
map<int, ciEntity*> mymap;
void main(void)
{
int x = 0;
class cObject *temp;
for(x = 0; x < 10; x++)
{
temp = new cObject;
temp->name = new char[25];
strcpy(temp->name, "Test");
temp->id=x;
mylist.push_back(*temp);
// now what with the map?
delete temp;
}
}
I’ve had other ideas too messing around with the map declaration. I’ve tried using an iter to go through the list and then mymap[id]=iter or similar variations. I’ve had zero luck getting anything to work. I know my fundamentals aren’t where they should be in regards to working with memory. Any help is appreciated!
I would alter this a little bit, and use something like a
std::shared_ptr<cObject>in both your list and your map. You can, for the map, use either anint, or possibly astd::stringfor the key-type, and then for the value-type, use thestd::shared_ptr<cObject>So your code would look more like:
If for some reason your compiler doesn’t have
std::shared_ptr, you can also get it from boost.The nice thing with this approach is that your list and map are now pointing to the same object, so if you change the object in the list, the changes will also be reflected in the map. Also the
shared_ptrobject will manage the life-time of the pointer through reference counting, so once there are no more references to the pointer, it will calldeleteon the pointer without you having to worry about cleaning up the pointers from each container (and avoiding ownership issues of the pointers as well).