简体   繁体   中英

Address of std::vector itself stable?

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

Thanks.

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

You can actually always assume that the address of a certain variable doesn't change, due to calling any behavior of it (that's not possible, since the language syntax prevents it. You cannot simply replace this with an arbitrary value).

Reallocation is a behavior of std::vector , that applies to it's underlying data structures (namely std::vector::data() ), and pointers taken from these overloads are unstable regarding this behavior and may change (same for any other addresses with offsets as taken eg from ptr = &myVector[5]; ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM