Do I need to call clear () when I am done with the vector?

All the questions I saw ask about memory management when vector elements are dynamically allocated / are pointers. My question concerns only the vector that was allocated on the stack by a simple type, for example int .

If I have the following code:

 std::vector<int> vec(5); for(int i = 0; i < vec.size(); i++) { std::cout << vec[i] << std::endl; } 

Do I need to call clear() when done?

+5
source share
2 answers

No.

C ++ classes have a destructor that is called when the class object goes out of scope or is deleted. Although you are correct that std::vector dynamically allocates space under the hood, the std::vector destructor will free up memory for you, which will lead to a happy program without leaks.

On the cppreference page, when the vector destructor is called ...

Destroys the container. Element destructors are called, and the storage used is freed. Note that if elements are pointers, objects with a pointer are not destroyed.


Also note that from cppreference on the cleanup function ...

Holds the capacity () of the vector unchanged ...

Therefore, when you call clear , the memory is not even freed! (see this SO question for more on what clear does)

+10
source

If you are concerned about freeing allocated memory (and therefore locked for use elsewhere) in a (large) vector , you should

  • make sure that the region / lifetime of the corresponding vector is limited to the region / time of its direct use, so that its destruction automatically frees up memory.

  • Otherwise (for some reason) you can

     vec.clear(); // reduces the size to 0, but not the capacity vec.shrink_to_fit(); // suggests to reduce the capacity to size assert(vec.capacity()==0); 

Note that vector::clear() cancels the allocation of memory in vector (only memory, if any, is dynamically allocated by vector elements). vector::shrink_to_fit() suggests reducing the size of the vector memory to the actual size, but an implementation may prefer to ignore this request.

Finally, the alternative to clear() , followed by shrink_to_fit() , is the swap idiom (which also works before C ++ 11):

 vector<Tp>().swap(vec); assert(vec.capacity()==0); 

What happens here is that a new empty vector (of the same type) is created and then immediately replaced with vec , so vec becomes empty (with zero size and capacity). Finally, since the new vector is a temporary (unnamed) object, it is destroyed, as a result of which the memory allocation is initially saved using vec .

+6
source

Source: https://habr.com/ru/post/1275634/


All Articles