Question

Just a quick question, if you have say:

using namespace std;

map< int, vector< string > > map1;

or maybe even:

map< int, map< int, vector< string > > > map2;

and just so you get the right idea:

map< int, map< int, map< int, vector< string > > > > map3;

if I do just:

map1.clear();
map2.clear();
map3.clear();

Is it safe in that it will empty everything in the map and its nested maps, vectors, lists, etc.?

Note: I know if you use pointers you need to manually go through and delete or if the map goes out of scope it should be fine too I'm only particularly interested in this case when in scope and on the stack.

Was it helpful?

Solution

Yes, a map will destruct all components.

If its components are STL containers, their destructors will clear the containers.

Read more about STL containers notably about destructor of std::map

OTHER TIPS

Yes this is perfectly safe. STL containers take care of memory management.

However, if you store pointers to objects which you allocated youself, you also have to delete them yourself:

std::vector<MyClass*> vec;
vec.push_back(new MyClass());
vec.clear(); // you get a memory leak here because you did not delete the object you allocated.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top