std::vector的地址本身稳定吗?
Address of std::vector itself stable?
如果我取一个std::vector
的地址,它在插入元素后重新分配,我可以假设它的地址没有改变吗?
谢谢。
是的,在 C++ 中您可以安全地假设。但是,第一个元素的地址&x[0]
可以改变,那些地址是不一样的。 编辑:当然其他元素的地址也是如此。
顺便说一句,第一个元素的地址是否可能保持或多或少的稳定取决于 whether or not the growth factor of the array is less than the golden ratio,这是了解 IMO 的一个非常酷的事实。
If I take the address of a std::vector
, and it reallocates after inserting elements, can I assume its address does not change?
你实际上可以总是假设某个变量的地址不会因为调用它的任何行为而改变(这是不可能的,因为语言语法阻止它. 您不能简单地将 this
替换为任意值)。
Reallocation 是 std::vector
的一种行为,适用于它的底层数据结构(即 std::vector::data()
),并且从这些重载中获取的指针是不稳定的关于此行为并且可能会更改(对于任何其他具有偏移量的地址也是如此,例如来自 ptr = &myVector[5];
)。
如果我取一个std::vector
的地址,它在插入元素后重新分配,我可以假设它的地址没有改变吗?
谢谢。
是的,在 C++ 中您可以安全地假设。但是,第一个元素的地址&x[0]
可以改变,那些地址是不一样的。 编辑:当然其他元素的地址也是如此。
顺便说一句,第一个元素的地址是否可能保持或多或少的稳定取决于 whether or not the growth factor of the array is less than the golden ratio,这是了解 IMO 的一个非常酷的事实。
If I take the address of a
std::vector
, and it reallocates after inserting elements, can I assume its address does not change?
你实际上可以总是假设某个变量的地址不会因为调用它的任何行为而改变(这是不可能的,因为语言语法阻止它. 您不能简单地将 this
替换为任意值)。
Reallocation 是 std::vector
的一种行为,适用于它的底层数据结构(即 std::vector::data()
),并且从这些重载中获取的指针是不稳定的关于此行为并且可能会更改(对于任何其他具有偏移量的地址也是如此,例如来自 ptr = &myVector[5];
)。