How to clean up a vector/map properly?

10,554

Solution 1

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.

Solution 2

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).

Share:
10,554
Martijn Courteaux
Author by

Martijn Courteaux

I'm writing Java, C/C++ and some Objective-C. I started programming in 2007 (when I was 11). Right now, I'm working on my magnum opus: an iOS, Android, OS X, Linux, Windows game to be released soon on all relevant stores. The game is written in C++ using SDL and OpenGL. A couple of seeds for my name (for java.util.Random, radix 26): 4611686047252874006 -9223372008029289706 -4611685989601901802 28825486102

Updated on June 04, 2022

Comments

  • Martijn Courteaux
    Martijn Courteaux almost 2 years

    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;