Suppose I have VectorA
and VectorB
are two std::vector<SameType>
, both initilized (i mean VectorA.size() > 0
and VectorB.size() > 0
)
If I do:
VectorA = VectorB;
the memory previosly allocated for VectorA
is automatically freed?
An std::vector manages its own memory. You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.
As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.
Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required.
The std::vector will automatically de-allocate the memory it uses.
It is freed in the sense that the destructors of all contained objects are called, and the vector no longer owns the memory.1
But really, it's just returned to the allocator, which may or may not actually return it to the OS.
So long as there isn't a bug in the allocator being used, you haven't created a memory leak, if that's what your concern is.
In general, not necessarily. When you assign one vector to the other, the post condition is that both arrays will contain equivalent objects at the end of the operation.
If the capacity
of the destination vector is enough, the operation can be achieved by calling the assignment operator on the set of min( v1.size(), v2.size() )
elements, and then either destructing the rest of the elements if the destination vector held more elements, or else copy-constructing the extra elements at the end. In this case no memory release or allocation will be done.
If the destination vector does not have enough capacity, then it will create a new buffer with enough capacity and copy-construct the elements in the new buffer from the source vector. It will then swap 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 released, but this is just one case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With