Alex Rivera | Logout

vector pointer locations guaranteed?

Asked 2012-01-05T04:49:32.663
8

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.

Edit
Report

1 Answer

2

When you use a vector's resize() or reserve() function to increase the capacity of the vector, it may need to reallocate memory for the array-backing. If it does reallocate, the new memory will not be located at the same address, so the address stored in oneNumber will no longer point to the right place.

Again, this depends on how many elements the vector is currently being used to store and the requested size. Depending on the specifics, the vector may be able to resize without reallocating, but you should definitely not assume that this will be the case.

answered 2012-01-05T04:57:32.677

Your Answer