Kharos
Kharos

Reputation: 63

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;

Upvotes: 5

Views: 4607

Answers (2)

sjrowlinson
sjrowlinson

Reputation: 3355

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.

Upvotes: 11

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

No, there is no need to call clear manually. It may or may not get called internally when the vector is destroyed, but any objects in the vector will get destroyed one way or the other as the vector is destroyed.

Upvotes: 3

Related Questions