vector::clear()
does not free memory allocated by the vector to store objects; it calls destructors for the objects it holds.
For example, if the vector uses an array as a backing store and currently contains 10 elements, then calling clear()
will call the destructor of each object in the array, but the backing array will not be deallocated, so there is still sizeof(T) * 10
bytes allocated to the vector (at least). size()
will be 0, but size()
returns the number of elements in the vector, not necessarily the size of the backing store.
As for your second question, anything you allocate with new
you must deallocate with delete
. You typically do not maintain a pointer to a vector for this reason. There is rarely (if ever) a good reason to do this and you prevent the vector from being cleaned up when it leaves scope. However, calling clear()
will still act the same way regardless of how it was allocated.