Sign in to follow this  

STL 2D Vectors and clear()

This topic is 3839 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
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
You might want to look into boost ptr_container

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

This topic is 3839 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this