Skip to main content
gamedev.net
🔒 Locked

std::vector::clear()

Started by Supernat02 4 replies 1.9k views
Original Post
Supernat02
Supernat02
I use the vector class to store pointers instead of entire classes, so that I can do the memory management myself and not have to copy an entire class when adding it to the vector. I'm not completely familiar with STL yet, so I may misunderstand it altogether. Anyhow, I create the vector with a pointer to a structure. When I call insert(), I pass the pointers in. What happens when I call vector::clear()? According to what I've read, it calls the destructors for classes. I'm a little confused about what memory management will take place with the call to clear(). I want to make sure I get the used memory de-allocated. I think it will just de-allocate the memory used to store the pointers, but I still have to destroy the referenced object. Is this true? Thanks in advance. Chris
Chris ByersMicrosoft DirectX MVP - 2005
Bincho
Bincho
You're going to have to manually delete each pointer. When you add an object to the vector class (not as a pointer, but actually adding an object) it will call the destructor of it when the vector itself is deleted or goes out of scope.
Rayno
Rayno
Quote:
Original post by Supernat02
I use the vector class to store pointers instead of entire I want to make sure I get the used memory de-allocated. I think it will just de-allocate the memory used to store the pointers, but I still have to destroy the referenced object. Is this true?


Yeah, thats true. If you used new to allocate memory for whatever your pointers point to, then you need to call delete yourself.

Or you could use something like auto_ptr, or boost::smart_ptr, and you wouldn't have to worry about it.
desertcube
desertcube
Quote:
Original post by Rayno
Or you could use something like auto_ptr, or boost::smart_ptr, and you wouldn't have to worry about it.


I agree about using smart pointers to take care of your memory, such as the boost one's you mentioned or Loki's (from Modern C++ Design, excelent book btw!), but you can not use auto_ptr!

Another alternative would be to impliment your own smart_ptr based on the above two libraries. Very easy to do and takes the worries about memory managment away (if used correctly).
Supernat02
Supernat02
Thanks everyone for confirming what I was thinking. :)

Chris
Chris ByersMicrosoft DirectX MVP - 2005
Rayno
Rayno
Quote:
Original post by desertcube
but you can not use auto_ptr!


Thanks for pointing that out. I didn't know that. I had always just used the boost pointers.

Topic Locked

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

Sign in to reply to this topic.