简体   繁体   中英

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.

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. 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:

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.

What's wrong?

TL;DR version:

An insertion operation can invalidate any pointers, references or iterators to elements of a std::vector .

Full explanation:

A std::vector has two useful metrics:

  • size , which is the number of elements stored.
  • capacity , which is the number of elements it's currently capable of storing.

capacity >= size at all times.

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.


* This is the typical internal implementation of a std::vector .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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