AlmostSurely
AlmostSurely

Reputation: 562

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.

Upvotes: 5

Views: 603

Answers (2)

Aleksei Averchenko
Aleksei Averchenko

Reputation: 1776

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.

Upvotes: 9

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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 e.g. from ptr = &myVector[5];).

Upvotes: 3

Related Questions