Re-allocating memory std :: vector

Suppose I have VectorA and VectorB - two std::vector<SameType> , both initialized (i mean VectorA.size() > 0 and VectorB.size() > 0 )

If I do this:

 VectorA = VectorB; 

VectorA memory previously allocated for VectorA automatically freed?

+6
source share
2 answers

It is freed in the sense that the destructors of all contained objects are called, and the vector no longer owns memory. 1

But in fact, he simply returned to the allocator , which may or may not actually return it to the OS.

Until an error is used in the used allocator, you did not create a memory leak if this is due to your problem.


<Sub> 1. As @David notes in a comment below, memory is not necessarily freed, depending on whether you need to resize or not.
+5
source

In general, optional. When you assign one vector to another, the post condition is that both arrays will contain equivalent objects at the end of the operation.

If the capacity target vector is sufficient, the operation can be performed by calling the assignment operator on the set of elements min( v1.size(), v2.size() ) , and then either destroying the remaining elements if the destination vector contains more elements, or copying additional elements in the end. In this case, freeing or allocating memory will not be performed.

If the target vector does not have sufficient capacity, it will create a new buffer with sufficient capacity and copy-construct the elements in the new buffer from the original vector. Then it will replace the old and new buffers, destroy all old objects and release the old buffer. In this case, the old objects are destroyed, and the old memory is freed, but this is just one case.

+2
source

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


All Articles