Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always call vector clear() at the end of the function?

I have some simple function that uses vector like this (pseudo code):

void someFunc(void) {      std::vector<std::string> contentVector;      // here are some operations on the vector      // should I call the clear() here or this could be ommited ?     contentVector.clear();  } 

Should I call the clear() or this could be ommited ?

like image 270
Michal Przybylowicz Avatar asked Feb 05 '14 03:02

Michal Przybylowicz


People also ask

Do we need to clear vector?

If you have a vector and it goes out of scope, all objects in the vector are destroyed. There isn't really a need to call clear() unless you want to dump the contents and reuse the vector.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Does std::vector clear call Delete?

So what your question should be: "Does std::vector<T*>::clear() call delete on its elements?" and here the answer is: No, it does not call delete . You have to do it manually like shown in your example code, or you can (and probably should) use objects like std::string or smart pointers instead of raw pointers.

Does vector erase call destructor?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


1 Answers

If we look at the cppreference.com entry for std::vector::~vector it says:

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.

so no you don't have to call clear.

If we want to go to the draft standard, we have to look at section 23.2.1 General container requirements paragraph 4 which says:

In Tables 96 and 97, X denotes a container class containing objects of type T, a and b denote values of type X,[...]

and then look at Table 96 — Container requirements which has the following expression entry:

(&a)->~X()   

and the following note:

note: the destructor is applied to every element of a; all the memory is deallocated.

Update

This is RAII in action and as Bjarne Stroustrup says in Why doesn't C++ provide a "finally" construct?:

Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.

like image 178
Shafik Yaghmour Avatar answered Sep 24 '22 04:09

Shafik Yaghmour