Advertisement

STD vector question

Started by June 22, 2001 04:06 AM
4 comments, last by Abdhl Al Hazred 23 years, 7 months ago
If I have this std vector: std::vector m_vFaces; Do I need to deallocate memory by my self when I dont´t need it or is it done when I call: m_vFaces.clear() Thanks, When the stars are right they will awake...
When the stars are right they will awake...
If you want to shrink the memory a vector uses you have to do it manually otherwise the vector will hang on to it''s allocated ram. This is a good thing from a speed point of view as it reduces the memory subsystem moving things around to help make things fit better.

If however you want to clear a buffer of it''s allocated ram dor this

m_vFaces.reserve(SizeInBytes);

If you want to see how much space it''s using use .capacity()

HTH


Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie
Advertisement
gimp, I think you should go read a little more on vector, some of your information is not correct.


Not sure what you mean by that gimp. the reserve function tells the vector to allocated enough memory for AT LEAST numberOfElems (not sizeInBytes). It will most likely allocate more to speed up the process. Remember that the stl has been designed for speed.

And capacity is the maximum number of objects the vector can have without having to reallocate memory.


Anyway to answer Abdhl Al Hazred, yes the vector will deallocate it`s memory without your need when it gets destroyed.

But warning : if you put pointers into the vector, the vector will only deallocated the memory of the pointer not of the object pointed to. So you need to destroy your pointers(by iterating through the vector and calling delete on your pointers), before the vector gets destroyed.

But when the vector stores other objects than pointers, you don`t need to worry about anything.



Edited by - Gorg on June 22, 2001 9:42:05 AM
Gorg is correct, vector will deallocate its memory on its destructor.

In fact, that is the only time vector deallocates its memory--though its internal pointers may read it''s empty, it has whatever memory has been used.

The following program returns 10:
  #include <vector>using namespace std;int main (){    vector<int> v(10);    v.clear ();    return v.capacity ();}  


Reserve does not free memory either. The destructor is the only member that actually releases all the memory (the assignment and reserve operators free memory after allocating more memory).
int main(){	std::vector vect;	[use vector]	return 0;} // descructor is called when we exit main, and vector efficiently cleans up 

For your class this will be called when your class is destroyed.
So don''t worry about vector, it does it''s job.
^ that''s my post
Accidently posted early and when I pressed back, IE cleared the UserName/Password fields.

This topic is closed to new replies.

Advertisement