Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

push_back can cause reallocation and moving of all elements in the vector, if the space that's currently assigned for element storage cannot contain the new element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top