There is absolutely no need to do that. std::vector
and all other containers automatically destroys their elements when they themselves would be destroyed. That means that their destructors are responsible for that action. So, don't.
The beauty of this is that containers are naturally exception safe[1]:
void someFunc(void) {
std::vector<std::string> contentVector;
// here are some operations on the vector
throw std::runtime_error("I just want to throw!");
contentVector.clear();
}
Will the line contentVector.clear();
be called? No. But you're still safe because it is guaranteed that contentVector
's destructor will be called.
From vector[2]:
Destructs the container. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed.
[1] You still need to make your elements exception safe though (have them properly free their resources whenever their destructors are called).
[2] See comments below for some thoughts on the SGI STL docs.