Jump to content
  • Advertisement
Sign in to follow this  
catch

STL 2D Vectors and clear()

This topic is 3994 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

Does this clean up properly? std::vector< std::vector<SomePointer*> > vec; .... SomeClass::~SomeClass { vec.clear(); } Does that properly destroy all the pointers, or do I have to iterate through the 2d vector and call clear for each element?

Share this post


Link to post
Share on other sites
Advertisement
It will destroy each of the "child" vectors, yes. Of course, it won't destroy the objects the pointers point to.

Share this post


Link to post
Share on other sites
Standard library containers look after THEIR memory. Automatically. You should almost never call .clear() explicitly; certainly not in a destructor, because it does nothing - if your object is destructed, then its members are destructed, and the container's destructor has the same effect as .clear() anyway.

YOU are expected to look after your memory. In your case, that would be the SomePointer instances that all those SomePointer*'s point at.

Note that in general, you can have several SomePointer*'s pointing at the same SomePointer, and your job is to arrange for EVERY SomePointer to get deallocated EXACTLY ONCE. This means finding ONE SomePointer* that points at each, and calling delete on it. Oh, and you also have to distinguish between scalar and array allocations: a new call MUST match a delete call, and a new[] call MUST match a delete[] call.

In general, this is hellish. Which is why you simplify your design when you can, use smart pointers and smart containers when you have to, and use raw pointers when you *really, really* have to, which is *almost never* in modern C++.

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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!