I have some code for you guru’s to check. I know this is probably ( definitely ) not the best way to go about deleting memory, but just let me know if it would potential be OK.
I know I should be using smart pointers, but I will do this in my next revision of the code.
Anyway here is my problem.
I have a class that is initiated each time in a loop. I pass this class pointer to a vectors of pointers to an object which also change in each iteration of the loop. e.x.
vector<A*>* ex_A
I then use these pointers to vectors in the class and Map them to each other by using
map< int, vector<B*>* >* ex_map.
This new map can then be accessed through the class by one of the public member functions.
At the end of Loop I wish to delete the memory so that the next new Class can be instantiated without seg faulting.
Here is some example code of what I am doing:
Inside Class MainClass.cxx
MainClass::MainClass(vector<A*>* ex_A, vector<B*>* ex_B, vector<C*>* ex_C): m_ex_A(ex_A), m_ex_B(ex_B), m_ex_C(ex_C) {}
MainClass::MakeMap(){
vector<A*>::iterator itr_A = m_ex_A->begin();
for(; itr_A != m_ex_A->end(); itr_A++){
//This member function returns a vector of B* that are dependent of A
vector<B*>* dependent_B = changeVectorB((*itr_A));
/Defined in Header File
//map< int, vector<B*>* >* m_mapAofB;
//Now get Map index of A with vector of B*
(*m_mapAofB)[(*itr_A)->Inedx()] = dependent_B;
}
}
I will want to delete m_mapAofB at some point so I would loop through each value of the map (which is a pointer to vector of pointers). I use something similar to this URL to achieve this.
C++ Generic code for deleting pointer value in Map and vector of pointers
My main concern is when to delete this memory, as MainClass will be in a for loop. Should I delete the memory at the end of each iteration of the for loop. This would allow for the new instantiation of the MainClass??
e.x.
for(int i = 0; i < 100000; i++){
//This will also change each loop
Vector<A*> ex1;
Vector<B*> ex2;
Vector<C*> ex3;
MainClass* ex_main = new MainClass(ex1,ex2,ex3);
///Do something....
//Finished with class now delete pointers
ex_main->DeleteMemory();
delete ex_main;
}
I’m confused on many levels by this and think it needs a redesign – but all that aside:
You state:
So, why do you believe you need to dynamically allocate MainClass in the first place if you’re planning on deleting the memory related to it at the end of each iteration? It can simply be a stack variable which is created at the top of the loop and destroyed each time it loops (or better yet, as described in Slade’s comment, you can declare it above your loop so it isn’t recreated every time – that would require you to have a public function to change it to mimic its constructor though). Secondly, wrap your pointers in objects (I don’t care if they’re smart pointers for real, just wrap them) so when your vectors go out of scope your wrappers destructors will automatically delete the dynamically allocated contents.