简体   繁体   English

std :: vector本身的地址稳定吗?

[英]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? 如果我获取std::vector的地址,并在插入元素后重新分配,我可以假设它的地址不会改变吗?

Thanks. 谢谢。

Yes, in C++ you can safely assume that. 是的,在C ++中你可以放心地假设。 However, the address of the first element &x[0] can change, those addresses are not the same. 但是,第一个元素&x[0]地址可以改变,这些地址不相同。 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. 顺便说一下,第一个元素的地址是否可能保持或多或少稳定取决于数组的增长因子是否小于黄金比例 ,这对于了解IMO来说是一个非常酷的事实。

If I take the address of a std::vector , and it reallocates after inserting elements, can I assume its address does not change? 如果我获取std::vector的地址,并在插入元素后重新分配,我可以假设它的地址不会改变吗?

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). 你实际上总是可以假设某个变量的地址没有改变,因为它调用了它的任何行为(这是不可能的,因为语言语法会阻止它。你不能简单地用任意值替换this )。

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]; ). 重新分配std::vector的行为,它适用于它的底层数据结构(即std::vector::data() ),并且从这些重载中获取的指针对于此行为是不稳定的并且可能会更改(对于任何其他地址都相同)例如来自ptr = &myVector[5]; )的偏移量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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