Martijn Courteaux
Martijn Courteaux

Reputation: 68847

How to clean up a vector/map properly?

If I have a vector<string*> *vect or a map<pair<string*, int*>, string*> *map,
how to clean up everything (including all object the vector/map contains)?
(Everything (vector, map, contents, string, ints) is allocated with new)

Is this enough:

delete vect;
delete map;

Upvotes: 3

Views: 12054

Answers (4)

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116256

No, you must iterate through the vector/ map, remove and delete its items one by one (which, as @SB pointed out, may require disposing of their members recursively).

(You could get away by simply deleting the items, if you are absolutely sure no one will access the vector elements anymore before the vector gets deleted - but it is still safer to remove each item before deleting it. This ensures program correctness at any point, eliminating the possibility for subtle bugs and easing maintenance in the long term.)

By the way this is one of the reasons why it is recommended to store smart pointers in collections, instead of raw pointers.

Upvotes: 7

ereOn
ereOn

Reputation: 55726

You really should consider using smart pointers.

vector<boost::shared_ptr<std::string> >* some_vector = new std::vector<boost::shared_ptr<std::string> >;

some_vector->push_back(boost::shared_ptr<std::string>("Hello World !"));

delete some_vector; // This will delete the contained std::string's as well
some_vector = NULL;

Basically, a smart pointer takes care of the life-cycle of the pointed data. They can even do much more (such a counting references, and so on) but I suggest you read this page to learn more about the different types of smart pointers.

You can even specify a custom "freeing" function to use, instead of the default (delete).

Upvotes: 4

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

You may want to consider Boost Pointer Container. It handles all the cleaning up and, in my experience, normal containers can seamlessly (meaning without breaking code) be replaced by these ones.

A pointer container expresses ownership of the contained objects by the container, which is what you have here (otherwise you wouldn't have to clean it up).

A container of smart-pointers is different, because the objects may live longer than the container. Also, there may be a small performance-penalty when using smart-pointers, but that really depends on the size of your containers and the type of operations you perform on them.

Upvotes: 0

user229044
user229044

Reputation: 239240

No, you must manually iterate over each container and call delete on the pointers it contains. The vector didn't allocate that memory, so it's not going to clean it up for you.

If you use smart pointers then the pointer itself will handle deallocating it's memory. Otherwise, you must balance your manual allocation with manual deallocation.

Upvotes: 0

Related Questions