1

I use a simple code:

std::vector < float > arr = { 3.42f, 6.45f, 53.43f };
float *elemPtr;
elemPtr = &arr[ 0 ];

std::cout << "elemPtr = " << *elemPtr << std::endl;
arr.push_back( 7.0f );
std::cout << "elemPtr = " << *elemPtr << std::endl;

And that code produces me following output:

elemPtr = 3.42
elemPtr = -6.25982e+18

Why does it happening after push_back? I didn't remove the first element of the vector. Why does it works like this?

I use Clang compiler (Xcode).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
JavaRunner
  • 2,455
  • 5
  • 38
  • 52

2 Answers2

12

push_back invalidates pointers, references, and iterators to existing elements.

That's because of the contiguity guarantee. push_back increases the size of the vector, and if the capacity of the internal buffer isn't sufficient to hold a new item immediately after the existing ones, in order to maintain contiguity, they all have to be moved to a new larger buffer.

If you want to continue accessing an element after future calls to push_back, your options are to access it by index in a vector, or use a container with no contiguity guarantee, such as std::list.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
5

The vector's storage got reallocated (to accommodate more elements in one contiguous block), invalidating all the pointers (and iterators).

Learn more about this here: http://en.cppreference.com/w/cpp/container/vector/push_back

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

szym
  • 5,606
  • 28
  • 34