delete heap vector of heap vectors

hi,
i've made the following vectors,
1
2
3
vector< vector<TreeElement*>* >* tempDirList = new vector< vector<TreeElement*>* >; //vector that holds pointers to other vectors
vector<TreeElement*>* tempFiles = new vector<TreeElement*>;
vector<TreeElement*>* tempDirs = new vector<TreeElement*>;

in the function that made these vectors returns the vector tempDirList,
now my question is, does the following code delete all my heaps?
1
2
vector< vector<TreeElement*>* >* tempDirList = listDir(pathRoot,showHiddenFiles); 
	delete tempDirList;
No, it deletes only the top-level vector. Why the heck would you want to allocate a vector on heap though?

because if i don't put it on a heap, i cant return to properly (i think)
Modern compilers should allow you to return a vector<> efficiently, thanks to NRVO (named return value optimization). This turned up in Visual Studio 2005 [1]; not sure when it arrived in GCC.

If you're not sure, you could pass the vector by reference as an out parameter.

I assume your orig. function def is (I've shortened the param names for display reasons)

vector< vector<TreeElement*>* >* listDir(const char* path, bool showHidden);

so change it to

void listDir(const char* path, bool showHidden, vector< vector<TreeElement*> >& results);

Note that I have also changed the outer vector to contain vectors not pointers to vectors, which removes your original problem. The vector's own memory allocator is already handling heap allocation (using std::allocator) so you were adding an extra unnecessary layer of indirection and memory allocation.

Andy

[1] http://msdn.microsoft.com/en-us/library/ms364057%28v=vs.80%29.aspx
Last edited on
Topic archived. No new replies allowed.