Is clearing a vector of a class containg vector enough to clear everything?

Viewed 69

Let's consider a class that contains a vector:

AGivenClass
{

public:

 vector< int > vec_int;

};

and let's consider that we have an instance, which is a vector of the class :

vector < AGivenClass > vec_instance;

My question is : Is doing

vec_instance.clear()

enough to free memory, including for the previously filled vec_int internal to the class ?

1 Answers

vec_instance.clear() will destoy all the contained objects, but won't deallocate memory buffer used to store them. Vector capacity won't change. So you also need to call vec_instance.shrink_to_fit() to make sure that all the memory is deallocated. Vector capacity should become 0 afterwards.

Related