Kharos Kharos - 3 months ago 12
C++ Question

do I have to clear std::vector before deleting it

So far I have always been using vector::clear() before deleting the vector. But is it necessary? Isn't the vector::clear() function called in destructor anyway?

// Consider I have this vector
std::vector<uint32_t>* myVector = new std::vector<uint32_t>(50);

... // vector gets filled

myVector->clear(); // <-- redundant??
delete myVector;
myVector = nullptr;

Answer

No, all elements of the std::vector are destructed upon std::vector destruction anyway so using clear is redundant. You can see the documentation for std::vector::~vector here.

Additionally, dynamically allocating the vector as you have done in the question is typically unnecessary - just initialise via

std::vector<uint32_t> myVector;
//...

then myVector and all it's elements will be destructed when it goes out of scope.

Comments