向量推回对元素地址的影响 [英] Effects of vector pushback on element address
问题描述
我有一个类对象的向量.一个函数随机选择两个元素并返回它们的地址.
I have a vector of class objects. A function randomly choses two elements and return their addresses.
现在使用这两个元素,我想生成两个相同类的新对象,并通过使用push_back将它们添加到向量中.
Now using these two elements, I want to generate two new objects of the same class and add them to the vector by using push_back.
这是两个父元素的地址:
Here is the address of the two parent elements:
这里没问题.然后生成第一个子对象,我使用vector_pushback将其添加到向量的末尾.问题是,在执行push_back命令之后,父对象的地址似乎已更改.这是push_back之后的调试器状态:
No problem here. The first child object is then generated, and I use vector_pushback to add it to the end of the vector. The problem is, after the push_back command has been executed, it seems like the addresses of the parent objects change. Here is the state of debugger after push_back:
如您所见,地址显然保持不变,但似乎它们指向push_back之后的垃圾值.据我了解,push_back在向量的末尾添加了一个元素.因此,我希望这两个元素的地址完全不变.
As you can see, the addresses obviously stay the same, but it seems like they point to garbage values after push_back. To my understanding, push_back adds an element at the end of the vector. Therefore I expect the address of the 2 elements to not change at all.
怎么了?
推荐答案
TL; DR版本:
插入操作可以使<元素的任何指针,引用或迭代器无效code> std :: vector .
完整说明:
std :: vector
具有两个有用的指标:
A std::vector
has two useful metrics:
容量> =大小
始终.
capability
是内部动态分配的数组的长度. * 插入元素时, size
递增1.但是一旦达到 capacity
,就必须分配一个更大的新数组(因此会增加 capacity
).这要求复制所有元素,并删除原始元素.所以他们所有的地址都改变了.
The capacity
is the length of the internal dynamically-allocated array.* When you insert an element, the size
increments by 1. But once it reaches capacity
, a new, larger array must be allocated (hence increasing the capacity
). This requires all the elements to be copied across, and the originals to be deleted. So all their addresses change.
*这是
std :: vector
的典型内部实现.
* This is the typical internal implementation of a
std::vector
.
这篇关于向量推回对元素地址的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!