How can I properly, and explicitly destroy std vector?

Here is how it is created.

std::vector<std::wstring> vData = StringSplit(sData,L',');// StringSplit returns a vector of wstring

Shortly after using and converting the contents of the container, I no longer need it, or want it hanging around in memory.
I don't want any pointers it may hold (if it does hold them, I don't no the guts of it) or the data in it or any of the elements in it.

The function in which the container is created (or returned to) does not go out of scope until the program ends, and I want to get shut explicitly.

I have searched the web, but all the answers I find are rather ambiguous, with some saying vData.clear() and others saying loop through with vData.erase(...). But the questions asked are rather in explicit too, and I'm finding it difficult to find a difinitive solution.

I appreciate your reading.

As long as the vector object itself is in scope, it takes up memory. But if you want to well and truly destroy the items stored by the vector and release the allocated memory, you use the swap trick:


You could also copy assign an empty vector, which can potentially be less performant than the swap trick, but has the benefit of clarity over the more obscure (if idiomatic) swap trick:

vData = std::vector<std::wstring>();

And invariably someone will chime in that the shiny new shrink_to_fit() method is available in C++11 for this very purpose:


But that's just a hint, and the compiler is not obligated to honor it and deallocate memory immediately.

This article has been dead for over six months. Start a new discussion instead.