Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory reallocation in vectors

Tags:

c++

I'm new to C++ and want to avoid newbie performance pitfalls.

Can erasing elements from a vector possibly cause a memory reallocation?

I'm working on a function that will add elements to a vector, and possibly erase some elements in the same frame.

like image 785
CPPapprentice Avatar asked May 20 '18 23:05

CPPapprentice


People also ask

Does vector resize allocate memory?

If you have used reserve() at the start to ensure there is already enough allocated memory, the size() of the vector will increase when you push_back() to it, but it will not allocate new memory again until it runs out of the space you reserved for it.

How does std::vector allocate memory How does its capacity grow?

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.

Do vectors cause memory leaks?

std::vector does not cause memory leaks, careless programmers do. You should also include an example that actually exhibits the behavior you are experiencing, including calls to the CRT debug API. There's a good possibility that you're incorrectly interpreting the leaks based on when they are reported.

Does vector clear deallocate memory?

No, memory are not freed. In C++11, you can use the shrink_to_fit method for force the vector to free memory. Show activity on this post.


1 Answers

No, it does not. If it did, it would invalidate all iterators, but, as cppreference states, it only Invalidates iterators and references at or after the point of the erase, including the end() iterator.

like image 174
Fureeish Avatar answered Sep 22 '22 12:09

Fureeish