Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of std::vector itself stable?

Tags:

c++

vector

If I take the address of a std::vector, and it reallocates after inserting elements, can I assume its address does not change?

Thanks.

like image 720
AlmostSurely Avatar asked Feb 02 '15 19:02

AlmostSurely


People also ask

Where does std::vector allocate memory?

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.

Is std::vector movable?

std::vector typically stores some pointers plus the allocator. When move-constructing a std::vector , only pointers and the allocator have to be moved. The elements don't need to be touched.

What does std::vector do?

1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.

Is vector stored continuous?

Yes. Yes, vector elements are contiguous, if you use c++11 you can also use the function T* data instead of the ugly cast to pass the underlying array to another function.


1 Answers

Yes, in C++ you can safely assume that. However, the address of the first element &x[0] can change, those addresses are not the same. Edit: the same is true for addresses of other elements, of course.


By the way, whether or not the address of the first element is likely to remain more or less stable depends on whether or not the growth factor of the array is less than the golden ratio, which is a really cool fact to know IMO.

like image 123
Alexei Averchenko Avatar answered Oct 02 '22 13:10

Alexei Averchenko