How to deallocate memory for different vector collections

So I have a few vector collections below that are in different files and I'm having trouble figuring out how to deallocate them. I have my attempts below and put them all in the same destructor to reduce space, but when I check for memory leaks there are a BUNCH of errors and leaks detected. I was wondering if someone could confirm if I'm freeing memory for each of the collections below correctly? I'm used to working with arrays instead so I've been confused.

Vectors declared in header file:
1
2
3
4
	vector<docCreator*>* docs; 
	vector<string>* menuOptions;
	static vector<Document*> elements; 
	static vector<Property<int>*> allNames; 

Destructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
	Control::~Control(){
		for (vector<docCreator *>::iterator i = docs->begin(); i != docs->end(); ++i) {
			delete *i;
		}
		docs->clear();
		delete docs;
		
		
		for(int i = 0; i < menuOptions.size(); ++i){ 
			delete menuOptions[i]; 
		}
			
		
		for(int i = 0; i < elements.size(); ++i){ 
			delete elements[i]; 
		}
		
		
		for(int j = 0; j < allNames.size(); ++i){
			delete allNames[j]; 
		}
		
	}
Hello eagerissac,

I believe that you are overthing this.

When a function looses scope any vector defined in that scope will automatically call the default dtor and destroy the vector before the function ends. This would apply to any STL class available and used in a program.

So unless you want to do something like:
1
2
3
4
Control::~Control()
{
    std::cout << "\n    Inside destructor\n\n";
}

There is no need to rewrite the default dtor.

Andy
to get rid of one at a time:
http://www.cplusplus.com/reference/vector/vector/erase/

if you want to delete all of them at once,
http://www.cplusplus.com/reference/vector/vector/clear/

if you are done with it, see if you can arrange the code so it goes out of scope when you are done, and it will free its own memory then.

the actual memory may stay in place (this is efficient, you don't want to reallocate to nothing then stick stuff back into it. If you want to FORCE it to release the memory:
use this after clear:
http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/

methods that resize (change capacity) vectors are inefficient by nature. It is best to avoid resizing them as much as possible.
Last edited on
Topic archived. No new replies allowed.