Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
like image 406
Kharos Avatar asked Dec 11 '22 15:12

Kharos


1 Answers

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.

like image 105
sjrowlinson Avatar answered Dec 13 '22 04:12

sjrowlinson