Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector pointer locations guaranteed?

Suppose I have a vector of ints,

std::vector<int> numbers;

that is populated with a bunch of values, then I say do this (where an entry exists at 43)

int *oneNumber = &numbers[43];

Is oneNumber guaranteed to always be pointing at the int at index 43, even if say I resize numbers to something like numbers.resize(46)?

I'm not 100% sure what expected behaviour is here, I know vectors are guaranteed to be contiguous but not sure if that continuity would also mean all the indices in the vector will remain in the same place throughout its life.

like image 770
meds Avatar asked Jan 05 '12 04:01

meds


2 Answers

Is oneNumber guaranteed to always be pointing at the int at index 43

Yes, this is guaranteed by the standard.

even if say I resize numbers to something like numbers.resize(46)?

No. Once you resize, add, or remove anything to the vector, all addresses and iterators to it are invalidated. This is because the vector may need to be reallocated with new memory locations.

like image 132
Mysticial Avatar answered Oct 03 '22 04:10

Mysticial


Your paranoia is correct. Resizing a std::vector can cause its memory location to change. That means your oneNumber is now pointing to an old memory location that has been freed, and so accessing it is undefined behavior.

like image 22
chrisaycock Avatar answered Oct 03 '22 03:10

chrisaycock