Friday 25 October 2019

c++ - Why did my pointer to a std::vector's element change its value after push_back()?




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


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...