Freeing memory from vector of structs
After I performed some operations on the vector of structs, I need to free the memory. I suppose clear() will not be sufficient, but I'm not sure how to perform individual delete.
Code:
typedef std::vector<VertexRAM> VecVertexRAM; // definition of a vector of structs
template <typename type>
void freeFromMemory(std::vector<type>& myVec) {
typename std::vector<type>::iterator myIter=myVec.begin();
while(myIter!=myVec.end()) {
delete(*myIter);
++myIter;
}
myVec.clear();
}
This outputs the following error:
Code:
error: type ‘struct VertexRAM’ argument given to ‘delete’, expected pointer
Any ideas on how to do this? Thanks
Re: Freeing memory from vector of structs
Any other suggestion on how to free the memory from the std::vector<VertexRAM> (which is a vector of structs) is very welcome.
What do you think of the following?(bottom of the page):
http://stackoverflow.com/questions/5...n-each-element
Thanks
Re: Freeing memory from vector of structs
You only need to delete what you create with new.
Re: Freeing memory from vector of structs
I dont create VertexRAM with 'new'. However, I wonder how to free the memory from a vector of structs.
Re: Freeing memory from vector of structs
Re: Freeing memory from vector of structs
clear() will set the size to 0 and call the destructors, but does not
change the capacity(). Search on "vector swap trick" :
Code:
template <typename type>
void freeFromMemory(std::vector<type>& myVec)
{
std::vector<type>().swap(myVec);
}
Re: Freeing memory from vector of structs
Quote:
Originally Posted by
onako
I dont create VertexRAM with 'new'. However, I wonder how to free the memory from a vector of structs.
You don't. The vector allocated the memory and the vector is responsible for cleanup. If you need to remove individual items you can do so using pop_back(). Otherwise you don't need to worry about it unless you just happen to have need of setting the vector back to 0 capacity.
Re: Freeing memory from vector of structs
If you're just inserting structures (not pointers to structures allocated on heap) into the std::vector, then you don't need to worry about freeing the memory used by the structures itself.
However, if you mean that the structure contains pointers, like this:
Code:
struct VertexRAM
{
int *something;
}
You will need to make sure that the memory is deallocated. The possible solutions are:
- Change the pointer to an smart pointer (if it's a pointer to one object) or to an (STL) collection (if it's a pointer to an array).
- Add a destructor to the structure.
- NOT RECOMMENDED: Before removing each item from the vector, call delete in the pointer. Complicates user code, and exceptions may result in memory leaks.