Skip to main content
GameDev.net gamedev.net
🔒 Locked

STL vector of pointers to objects

Started by joeG Nov 19, 1999 at 2:52 PM 0 replies 700+ views
Original Post
joeG
joeG
OK, since my last post on this same topic I've become a little bit more knowledgable about STL's vector class. Here's the problem though,
I have a vector whose elements are pointers to objects. Documentation says that an erase will not deallocate memory allocated to that object (for the reason that the vector controls its own memory not the memory of the pointer of the object).
How do I deallocate the memory that my object is using from vector?
joeG
Aidan
Aidan
The STL vector allocates the memory which it allocated, but not what you allocated with new... and then inserted as pointer into the vector

To delete the contents of a vector you have to go throught it and delete the memory the pointer points to and then let the vector do the rest.

=> if you want to erase !and! delete member n
delete stl_vector_object[n]; // delete memory
stl_vector_object.erase( n /* position n */ );

In a destructor you should write sth. like :

for ( int i = 0; i < stl_vector_object.size(); ++i )
{
delete stl_vector_object[i];
}
stl_vector_object.clear();

-> Aidan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.