If I take the address of a std::vector
, and it reallocates after inserting elements, can I assume its address does not change?
Thanks.
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.
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.
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.
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.
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.
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