简体   繁体   English

矢量后推对元素地址的影响

[英]Effects of vector pushback on element address

I have a vector of class objects.我有一个类对象的向量。 A function randomly choses two elements and return their addresses.一个函数随机选择两个元素并返回它们的地址。

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.现在使用这两个元素,我想生成同一类的两个新对象,并使用 push_back 将它们添加到向量中。

Here is the address of the two parent elements:这是两个父元素的地址:

No problem here.这里没问题。 The first child object is then generated, and I use vector_pushback to add it to the end of the vector.然后生成第一个子对象,我使用 vector_pushback 将它添加到向量的末尾。 The problem is, after the push_back command has been executed, it seems like the addresses of the parent objects change.问题是,在执行 push_back 命令后,父对象的地址似乎发生了变化。 Here is the state of debugger after 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.如您所见,地址显然保持不变,但它们似乎指向 push_back 之后的垃圾值。 To my understanding, push_back adds an element at the end of the vector.据我了解,push_back 在向量的末尾添加了一个元素。 Therefore I expect the address of the 2 elements to not change at all.因此,我希望这两个元素的地址根本不会改变。

What's wrong?怎么了?

TL;DR version: TL;DR 版本:

An insertion operation can invalidate any pointers, references or iterators to elements of a std::vector . 插入操作可以使指向std::vector元素的任何指针、引用或迭代器无效。

Full explanation:完整解释:

A std::vector has two useful metrics: std::vector有两个有用的指标:

  • size , which is the number of elements stored.size ,这是存储的元素数。
  • capacity , which is the number of elements it's currently capable of storing. capacity ,这是它当前能够存储的元素数量。

capacity >= size at all times. capacity >= size始终。

The capacity is the length of the internal dynamically-allocated array. capacity是内部动态分配数组的长度。 * 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 ). *当您插入一个元素时, size增加 1。但是一旦达到capacity ,就必须分配一个新的更大的数组(因此增加capacity )。 This requires all the elements to be copied across, and the originals to be deleted.这需要复制所有元素,并删除原始元素。 So all their addresses change.所以他们所有的地址都改变了。


* This is the typical internal implementation of a std::vector . * 这是std::vector的典型内部实现。

如果当前分配给元素存储的空间不能包含新元素, push_back会导致重新分配和移动向量中的所有元素。

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

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