Jump to content
  • Advertisement
Sign in to follow this  
thecoast47

vector Clear method....C++

This topic is 2557 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Lets say i have a vector of type CAT* and i add 3 cat pointers to the array:

int main(){
std::vector<CAT*> CAT_LIST;
CAT_LIST.push_back(new CAT());
CAT_LIST.push_back(new CAT());
CAT_LIST.push_back(new CAT());
}

So my question is.... can i just call the .clear() method in order to delete and remove pointers from the vector ?
-or- do i have to loop through the vector and call the delete keyword on every pointer and then clear the null pointers from the list like this:

int main(){
for (int K = 0 ; K < (int)CAT_LIST.size();K++){
delete CAT_LIST[K];
}
CAT_LIST.clear();
}

Share this post


Link to post
Share on other sites
Advertisement
You have to loop through and delete each object the pointers point to. Vectors simply destruct the objects they contain. In this case it contains pointers, which have no destructor, so destroying one doesn't do much.

Or use a type to hold your pointer that deletes the object in its destructor (a "smart pointer")

Also, negative sizes or indices don't make sense, so use unsigned types for sizes/indexes. Preferably std::size_t so things like porting 32bit->64bit are far less painful.

Share this post


Link to post
Share on other sites
Small tip: use iterators to loop over the vector instead of indices, and you don't need to worry about no signs.

for (std::vector<CAT*>::iterator i = CAT_LIST.begin(), end = CAT_LIST.end(); i != end; ++i)
delete *i;
CAT_LIST.clear();


[font="CourierNew, monospace"] [/font]

Share this post


Link to post
Share on other sites
or use boost::ptr_vector which internally stores pointers but act like a normal vector.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!